【问题标题】:How to sort Map by value in desc and key in natural order at the same time in Java 8如何在Java 8中同时按自然顺序按desc中的值和键对Map进行排序
【发布时间】:2020-03-16 23:22:23
【问题描述】:

有任何方法可以在同一操作中按键和值对 Map 进行排序。 地图有值{hover=1, solar=1, waterproof=3, storage=1, battery=2}

所以排序后的值应该是

{waterproof=3, battery=2, hover=1, solar=1, storage=1}

我正在努力

    Map mp = map.entrySet().stream()
            .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
            (newValue,oldValue) -> oldValue, LinkedHashMap::new))
        //.sorted(Map.Entry.comparingByKey())           
        //.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
        //(newValue,oldValue) -> oldValue, LinkedHashMap::new))
            ;

【问题讨论】:

    标签: java lambda collections java-8 java-stream


    【解决方案1】:

    使用thenComparing 创建比较器链:

    Map mp = map.entrySet().stream()
                .sorted(Collections.reverseOrder(Map.Entry.<String, Integer>comparingByValue())
                        .thenComparing(Map.Entry.comparingByKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (newValue, oldValue) -> oldValue, LinkedHashMap::new));
    

    请注意,在这种情况下,您需要为第一个比较器指定显式类型参数,因为编译器无法在如此复杂的情况下推断类型。

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 1970-01-01
      • 2020-03-19
      • 2010-10-29
      • 2023-04-04
      • 1970-01-01
      • 2014-04-03
      • 2015-04-06
      相关资源
      最近更新 更多