Sorting Descending order: Java Map(降序排序:Java Map)
问题描述
我想做的是按值对地图进行排序.我查看了 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:降序排序:Java Map
基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01