Package com.zuidaima.util;
Import Java.util.Comparator;
Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.TreeMap;
public class Valuecomparator implements comparator<long> {map<long, double> base;
Public Valuecomparator (Map<long, double> base) {this.base = base; public int Compare (long A, long B) {if Base.get (a). Doublevalue () >= Base.get (b). Doublevalue (
) {return-1;
else {return 1;
} public static <k, V extends comparable<v>> map<k, v> sortbyvalues ( Final map<k, v> Map) {comparator<k> valuecomparator = new comparator<k> () {Pub
Lic int compare (k K1, K K2) {int compare = Map.get (K2). CompareTo (Map.get (K1));
if (compare = = 0) return 1; ElSe return compare;
}
};
Map<k, v> sortedbyvalues = new treemap<k, v> (Valuecomparator);
Sortedbyvalues.putall (map);
return sortedbyvalues; public static void Main (string[] args) {hashmap<long, double> map = new Hashmap<long, D
Ouble> ();
Map.put (1l, 99.5);
Map.put (2l, 67.2);
Map.put (3l, 67.5);
Map.put (4l, 67.6);
Valuecomparator BVC = new Valuecomparator (map);
Treemap<long, double> sorted_map = new Treemap<long, double> (BVC);
SYSTEM.OUT.PRINTLN ("unsorted map:" + map);
Sorted_map.putall (map);
System.out.println ("Results:" + sorted_map);
Map<long, double> sorted_map2 = sortbyvalues (map);
System.out.println ("results2:" + sorted_map2); }
}
Output results:
Unsorted map: {1=99.5, 2=67.2, 3=67.5, 4=67.6}
Results: {1=99.5, 4=67.6, 3=67.5, 2=67.2}
Results2: {1=99.5, 4=67.6, 3=67.5, 2=67.2}
The principle of comparing the size of the key is similar, we rewrite the good. Enjoy it.
Original: http://www.zuidaima.com/share/1830834176347136.htm
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/