问题描述
我想做的是按值对地图进行排序.我查看了 stackoverflow 网站上提供的许多问题,并发现以下解决方案可以满足我的需求,但缺少一个小东西.
What I want to do is sort a map by value. I went over many questions that are available on the stackoverflow site and found out following solution that does what I want but missing a small thing.
Link1:排序图
但我遇到的问题是,默认情况下这是按值升序排序的.我想按降序排列:
But the issue I am running into is that by default this is sorted by ascending order by value. I want to order it by descending order:
所以我所做的是我创建了一个实现比较器的类
So what I did was I created a class that implements a comparator
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));
}
}
然后我将我的地图传递给树形图,
And then I pass my map to the treemap,
MyComparator comp = new MyComparator(myMap);
Map<String, Integer> newMap = new TreeMap(comp);
newMap.putAll(myMap);
这似乎是一种不好的方法,因为我觉得这效率低下.有没有办法将链接中的解决方案更改为默认按降序排序.
This seems like bad approach because I feel this is inefficient. Is there a way to change the solution in the link to do ordering on descending order by default.
推荐答案
你应该使用 new TreeMap<>(Collections.reverseOrder());
.
Map<String, Integer> newMap = new TreeMap<>(Collections.reverseOrder());
newMap.putAll(myMap);
或反转现有的比较器,如值比较器 Collections.reverseOrder(comparator)
.它的工作方式类似于您在调用 compare
/compareTo
之前交换两个对象的方法.
or to reverse an existing comparator like the value-comparator Collections.reverseOrder(comparator)
. It works like your approach swapping the two objects before invoking compare
/compareTo
.
这篇关于降序排序:Java Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!