首页 > 解决方案 > 如何根据值按降序对 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);

我想要的结果示例:

-或者-

标签: javasortinghashmap

解决方案


这是使用流 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}


推荐阅读