我想写一个比较器,让我按值而不是默认的自然顺序对TreeMap进行排序.
我试过这样的东西,却找不到出了什么问题:
import java.util.*;
class treeMap {
public static void main(String[] args) {
System.out.println("the main");
byValue cmp = new byValue();
Map<String, Integer> map = new TreeMap<String, Integer>(cmp);
map.put("de",10);
map.put("ab", 20);
map.put("a",5);
for (Map.Entry<String,Integer> pair: map.entrySet()) {
System.out.println(pair.getKey()+":"+pair.getValue());
}
}
}
class byValue implements Comparator<Map.Entry<String,Integer>> {
public int compare(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2) {
if (e1.getValue() < e2.getValue()){
return 1;
} else if (e1.getValue() == e2.getValue()) {
return 0;
} else {
return -1;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想我要问的是:我可以Map.Entry传递给比较器吗?
我需要一个可以按其值的递减顺序迭代的Map .是否有像Apache Commons或Guava这样的标准库提供这种地图?