你不能拥有TreeMap
本身对值进行排序,因为这违背了SortedMap规格:
A Map
这进一步提供了总排序 on its keys.
但是,使用外部集合,您始终可以排序Map.entrySet()无论您希望什么,可以通过键、值,甚至两者的组合(!!)。
这是一个返回一个通用方法SortedSet
of Map.Entry
,给定一个Map
其值为Comparable
:
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()
is.
一般来说,按值对映射条目进行排序的需求并不典型。
Note on ==
for Integer
你原来的比较器比较Integer
using ==
。这几乎总是错误的,因为==
with Integer
操作数是引用相等,而不是值相等。
System.out.println(new Integer(0) == new Integer(0)); // prints "false"!!!
相关问题
-
在Java中比较两个整数时会发生自动拆箱吗? (NO!!!)
-
是否保证new Integer(i) == i在Java中?(是的!!!)