【问题标题】:Sorting the Map in descending order based on the value and sort the key in ascending order if value is duplicate根据值按降序对 Map 进行排序,如果值重复则按升序对键进行排序
【发布时间】:2021-10-12 14:20:07
【问题描述】:

我正在使用映射接口从文件中读取,然后将其中的值存储为键值对。

Map<String, Integer> map = new HashMap<>();

值为

A 25
D 10
B 15
E 15
C 17

我想首先按值降序排列Sorting the Map<Key,Value> in descending order based on the value 。这将有助于实现降序排列。但是如果值是重复的,我想按键按升​​序排序。

预期输出

A 25
C 17
B 15
E 15
D 10

有谁知道如何做到这一点。

【问题讨论】:

    标签: java android hashmap


    【解决方案1】:

    您可以使用Comparator.comparingthenComparing 以正确的顺序进行排序。流可用于将新的Map 排序和收集到LinkedHashMap 以保留新的顺序。

    Map<String, Integer> map = Map.of("A", 25, "D", 10, "B", 15, "E", 15, "C", 17);
    Map<String, Integer> result = map.entrySet().stream()
        .sorted(Comparator.<Map.Entry<String, Integer>>comparingInt(Map.Entry::getValue)
           .reversed().thenComparing(Map.Entry::getKey))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
             (a,b)->b, LinkedHashMap::new));
    System.out.println(result);
    

    Demo

    【讨论】:

    • 你能解释一下吗。sorted(Comparator.&lt;Map.Entry&lt;String, Integer&gt;&gt;comparingInt(Map.Entry::getValue) .reversed().thenComparing(Map.Entry::getKey))这部分
    • 这部分也是.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a,b)-&gt;b, LinkedHashMap::new))
    • @vivekmodi Comparator.comparingInt 在这里用于按每个条目的值进行排序,我们调用reversed 得到降序(升序是默认值)。 thenComparing 用于在值相同的情况下按升序对键进行排序。 Collectors.toMap 这里只是将条目流转换为LinkedHashMap。有关详细信息,请参阅文档。
    【解决方案2】:

    作为已接受答案的替代方案,我将提取 IMO 使其更具可读性的比较器,例如:

    Map<String, Integer> map = Map.of("A", 25, "D", 10, "B", 15, "E", 15, "C", 17);
    
    Comparator<Map.Entry<String,Integer>> byValueDesc = Map.Entry.comparingByValue(Comparator.reverseOrder());
    Comparator<Map.Entry<String,Integer>> byKeyAsc = Map.Entry.comparingByKey();
    
    Map<String, Integer> result =
    
        map.entrySet()
                .stream()
                .sorted(byValueDesc.thenComparing(byKeyAsc))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2)->e1, LinkedHashMap::new));
    

    【讨论】:

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