java - 如何根据值按降序对 HashMap 进行排序?
问题描述
我正在尝试HashMap
根据值对 a 进行排序,使其按降序排列。但我不知道如何实现它。我该怎么做呢?
HashMap<K, Integer> keysAndSizeMap = new HashMap<>();
for (K set : map.keySet()) {
keysAndSizeMap.put(set, map.get(set).size());
}
// implementation here?
System.out.println("keysAndSizeMap: " + keysAndSizeMap);
我想要的结果示例:
- 输入:
{800=12, 90=15, 754=20}
- 输出:
{754=20, 90=15, 800=12}
-或者-
- 输入:
{"a"=2, "b"=6, "c"=4}
- 输出:
{"b"=6, "c"=4, "a"=2}
解决方案
这是使用流 API 按值对地图进行排序的一种方法。请注意,生成的映射是LinkedHashMap
其值的降序排列。
Map<Integer, Integer> map = new HashMap<>();
map.put(1, 10);
map.put(12, 3);
map.put(2, 45);
map.put(6, 34);
System.out.println(map);
LinkedHashMap<Integer, Integer> map2 =
map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(e -> e.getKey(),
e -> e.getValue(),
(e1, e2) -> null, // or throw an exception
() -> new LinkedHashMap<Integer, Integer>()));
System.out.println(map2);
输入:{1=10, 2=45, 6=34, 12=3}
输出:{2=45, 6=34, 1=10, 12=3}
推荐阅读
- python - 我想从excel导入数据,把它放在python中的字典列表中,然后覆盖excel中的数据
- excel - 使用 VBA 改变应用程序焦点
- javascript - 如何使用 dataTables.js 库显示“Showing 1 of N Entries”?
- c++ - ESP32 和 Kotlin 服务器之间的套接字延迟不一致
- mysql - 有没有比 LEFT JOIN 更好的方法在 MYSQL 中将两个表连接在一起?它非常慢
- python - 如何在 DJango 中实现分支权限管理模型?
- tableau-api - Tableau 中子字符串的出现次数
- php - 如何从输出中获取特定的字符串值?
- python - 如何从 IntgerField(Timestamp) 转换为 python datetime
- ios - 根据另一个变量的值更改变量的值