我是Java的新手,经常发现我需要对Map<Key, Value>值进行排序.
由于值不是唯一的,我发现自己将其转换keySet为a array,并通过数组排序对该数组进行排序,并使用自定义比较器对与键关联的值进行排序.
有没有更简单的方法?
我想写一个比较器,让我按值而不是默认的自然顺序对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传递给比较器吗?