你不能
TreeMap对值本身进行排序,因为这违反了
SortedMap规范:
一个Map是还提供了一个总体排序它的键。
但是,使用外部集合,你始终
Map.entrySet()可以根据需要按键,值或什至两者的组合(!!)进行排序。
这是一个通用方法,如果的值为,则返回的
SortedSetof :Map.EntryMapComparable
static <K,V extends Comparable<? super V>>SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) { SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>( new Comparator<Map.Entry<K,V>>() { @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) { int res = e1.getValue().compareTo(e2.getValue()); return res != 0 ? res : 1; } } ); sortedEntries.addAll(map.entrySet()); return sortedEntries;}现在,你可以执行以下操作:
Map<String,Integer> map = new TreeMap<String,Integer>(); map.put("A", 3); map.put("B", 2); map.put("C", 1); System.out.println(map); // prints "{A=3, B=2, C=1}" System.out.println(entriesSortedByValues(map)); // prints "[C=1, B=2, A=3]"请注意,如果你尝试修改
SortedSet自身或
Map.Entry内部,则将发生时髦的事情,因为它不再像原来那样
entrySet()是原始地图的“视图” 。
一般而言,按地图的值对地图的条目进行排序的需求是不典型的。
Note on == for Integer
你的原始比较器
Integer使用比较
==。这几乎总是错的,因为==有Integer操作数是一个参考平等,没有平等的价值。
System.out.println(new Integer(0) == new Integer(0)); // prints "false"!!!



