首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java 8中同时按值和键的自然顺序对Map进行排序

如何在Java 8中同时按值和键的自然顺序对Map进行排序
EN

Stack Overflow用户
提问于 2019-11-21 13:37:58
回答 1查看 252关注 0票数 3

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

所以在排序后,值应该是

代码语言:javascript
复制
{waterproof=3, battery=2, hover=1, solar=1, storage=1}

我正试着像

代码语言:javascript
复制
    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))
            ;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-21 13:47:44

使用thenComparing创建比较器链

代码语言:javascript
复制
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));

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58967948

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档