排序降序:Java地图 [英] Sorting Descending order: Java Map
问题描述
我想要做的是按价值排序地图。我回顾了很多在stackoverflow站点上可用的问题,并发现了下面的解决方案,它可以做我想做的事情,但缺少一件小事。
Link1 :Sorting Map但是我遇到的问题是,默认情况下,这是按值升序排列的。我想按降序排列:
所以我做的是我创建了一个实现比较器的类
class MyComparator实现比较器{
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));
然后我将地图传递给树形图, / p>
MyComparator comp = new MyComparator(myMap);
Map< String,Integer> newMap = new TreeMap(comp);
newMap.putAll(myMap);
这看起来很糟糕,因为我觉得这样做效率不高。有没有办法改变链接中的解决方案以默认降序排序。 >。
地图< String,Integer> newMap = new TreeMap(Collections.reverseOrder());
newMap.putAll(myMap);
或反转现有的比较器,如值比较器 Collections.reverseOrder比较器)
它的作用就像在调用 compare
/ compareTo
<>之前交换两个对象。 / p>
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: Sorting Map
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.
You should use new TreeMap(Collections.reverseOrder());
.
Map<String, Integer> newMap = new TreeMap(Collections.reverseOrder());
newMap.putAll(myMap);
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地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!