我想写一个比较器,让我按值而不是默认的自然顺序对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传递给比较器吗?
我们如何排序HashMap<key, ArrayList>?
我想根据一个值来排序ArrayList.
我想要一个可以计算我拥有的对象数量的类 - 听起来收集所有对象然后对它们进行分组会更有效.
Python在collections.Counter中有一个理想的结构,Java或Scala有类似的类型吗?