Java根据map的value降序排序
时间: 2024-01-25 16:03:39 浏览: 92
下面是Java根据map的value降序排序的示例代码:
```java
// 创建一个Map对象
Map<String, Integer> map = new HashMap<>();
map.put("A", 10);
map.put("B", 5);
map.put("C", 8);
map.put("D", 3);
// 将Map转换为List
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
// 使用Collections.sort方法对List进行排序
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
// 根据value降序排序
return o2.getValue().compareTo(o1.getValue());
}
});
// 遍历排好序的List
for (Map.Entry<String, Integer> entry : list) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
```
输出结果:
```
A: 10
C: 8
B: 5
D: 3
```
阅读全文
相关推荐


















