首先自己写一个比较器,实现Comparator接口,自己写一个构造方法,将一个map集合传递进去。
class ValueComparator implements Comparator<String> {
private Map<String, Long> map;
public ValueComparator(Map<String, Long> map) {
super();
this.map = map;
}
@Override
public int compare(String o1, String o2) {
if (map.get(o1) > map.get(o2)) {
return -1;
} else {
return 1;
}
}
}
使用代码
private Map<String, Long> sortResult(Map<String, Long> result) {
Map<String, Long> treeResult = new TreeMap<String, Long>(new ValueComparator(result));
treeResult.putAll(result);
return treeResult;
}
将需要排序的map集合传递给比较器,再将result中的键值对put到TreeMap中就行了。