【问题标题】:How to sort a HashMap based on values in descending order?如何根据值按降序对 HashMap 进行排序?
【发布时间】:2019-04-12 04:38:35
【问题描述】:

我正在尝试根据HashMap进行排序,使其按降序排序。但我不知道如何实现它。我该怎么做呢?

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}

【问题讨论】:

标签: java sorting hashmap


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用 TreeSet 和自定义比较器对条目进行排序,并使用 Java 8 流来创建排序映射。

    TreeSet<Entry<T, Integer>> sortedEntrySet = new TreeSet<Entry<T, Integer>>((e1, e2) -> e2.getValue() - e1.getValue());
    sortedEntrySet.addAll(keysAndSizeMap.entrySet());
    Map<T, Integer> sortedMap = sortedEntrySet.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      相关资源
      最近更新 更多