[英]Sorting Descending order: Java Map
我想要做的是按值排序地图。 我找了很多关于stackoverflow网站上可用的问题,并找到了以下解决方案,它做了我想要的但却错过了一件小事。
Link1 :排序地图
但我遇到的问题是默认情况下按值按升序排序。 我想按降序排序:
所以我做的是创建了一个实现比较器的类
class MyComparator implements Comparator {
Map map;
public MyComparator(Map map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
return ((Integer) map.get(o2)).compareTo((Integer) map.get(o1));
}
}
然后我将我的地图传递给树图,
MyComparator comp = new MyComparator(myMap);
Map<String, Integer> newMap = new TreeMap(comp);
newMap.putAll(myMap);
这似乎是不好的方法,因为我觉得这是低效的。 有没有办法在链接中更改解决方案,默认情况下按降序排序。
你应该使用new TreeMap<>(Collections.reverseOrder());
。
Map<String, Integer> newMap = new TreeMap<>(Collections.reverseOrder());
newMap.putAll(myMap);
或者反转现有的比较器,如值比较器Collections.reverseOrder(comparator)
。 它的工作方式类似于在调用compare
/ compareTo
之前交换两个对象的方法。
TreeMap<Long,String> treeMap = new TreeMap<Long,String>();
NavigableMap <Long, String> nmap = treeMap.descendingMap();
Set<Long, String> set = nmap.entrySet();
Iterator<Long, String> iterator = set.iterator();
现在你可以迭代迭代器并使用iterator.hasNext()和iterator.next()方法提取值......
这将有效:
TreeMap<Integer, Integer> reverseInteger=new TreeMap<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2>o1?1:o2==o1?0:-1;
}
});
您可以通过在开头添加减号来简单地反转比较方法的返回值:
return -((Integer) map.get(o2)).compareTo((Integer) map.get(o1));
要更改链接中的解决方案以按降序排序,只需反转条件:
...
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return 1; // For ascending, return -1;
} else {
return -1; // For ascending, return 1;
} // returning 0 would merge keys
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.