1.使用TreeMap<K,V>实现对Map<K,V>排序
TreeMap中,是实现了对key的排序,不能根据value的大小来排序,其中的K,必须实现一个可比较的接口。
1. TreepMap通过传入比较器的构造方法
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
2.也可以通过comparator()方法传入
public Comparator comparator() {
return comparator;
}
3.在向TreeMap中put元素时实现了根据key来排序
510 public V put(K key, V value) {
…………
525 // split comparator and comparable paths
526 Comparator cpr = comparator;
527 if (cpr != null) {
528 do {
529 parent = t;
530 cmp = cpr.compare(key, t.key);
531 if (cmp < 0)
532 t = t.left;
533 else if (cmp > 0)
534 t = t.right;
535 else
536 return t.setValue(value);
537 } while (t != null);
538 }
539 else {
540 if (key == null)
541 throw new NullPointerException();
542 Comparable k = (Comparable ) key;
543 do {
544 parent = t;
545 cmp = k.compareTo(t.key);
546 if (cmp < 0)
547 t = t.left;
548 else if (cmp > 0)
549 t = t.right;
550 else
551 return t.setValue(value);
552 } while (t != null);
553 }
…………
563 }
2.根据Value值对Map排序
同样Map<K,V>中的V也发现可比较,即实现了comparable接口,示例如下:
1.实现了comparable接口的对象
11 public class Music implements Comparable,Serializable{
12 …………
128 public int compareTo(Music o) {
129 int i = o.getPeakTime().compareTo(this.getPeakTime()); //倒序
130 if(i==0){
131 i = o.getNum().compareTo(this.getNum());
132 if(i == 0){
133 i = o.getNeid().compareTo(this.getNeid());
134 }
135 }
136 return i;
137 }
138 …………
169 }
2.排序
3.排序的方法
14 public class MapUtil {
15
16 …………
24 public static> Map sortByValue( Map map ){
25 List> list =
26 new LinkedList>( map.entrySet() );
27 Collections.sort(list, new Comparator>() {
28 public int compare(Map.Entryo1, Map.Entry o2) {
29 int res = o1.getValue().compareTo(o2.getValue());
30 return res != 0 ? res : 1; // 处理当value相等时,不丢失元素
31 }
32 });
33 Mapresult = new LinkedHashMap ();
34 for (Map.Entryentry : list){
35 result.put( entry.getKey(), entry.getValue() );
36 }
37 return result;
38 }
39 …………
63 public static> SortedSet > entriesSortedByValues(Map map) {
64 SortedSet> sortedEntries = new TreeSet >(
65 new Comparator>() {
66 @Override public int compare(Map.Entrye1, Map.Entry e2) {
67 int res = e1.getValue().compareTo(e2.getValue());
68 return res != 0 ? res : 1; // Special fix to preserve items with equal values
69 }
70 }
71 );
72 sortedEntries.addAll(map.entrySet());
73 return sortedEntries;
74 }
75 …………
76 public static void main(String[] args){
77 MapnonSortedMap = new HashMap ();
78 …………
96
97 // nonSortedMap.put("aaa", 1);
98 // nonSortedMap.put("ddd", 3);
99 // nonSortedMap.put("ccc", 1);
100 // nonSortedMap.put("rrrr", 2);
101
102 MapsortedMap = MapUtil.sortByValue(nonSortedMap);
103 for(Map.Entryentry : sortedMap.entrySet()){
104 System.out.println(entry.getKey()+":"+entry.getValue());
105 }
106 // for (Map.Entryentry : entriesSortedByValues(nonSortedMap)) {
107 // System.out.println(entry.getKey()+":"+entry.getValue());
108 // }
109 }
110 }