云迈博客

您现在的位置是:首页 > 后端开发 > Java > 正文

Java

Java8 Map 按Key排序和按Value排序

游荡2020-10-29Java759
java8以上的做法按key排序```Mapmap=newHashMap();map.put(“KFC”,“kfc”);map.put(“WNBA”,“wnba”);map.put

java8以上的做法

按key排序

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

map.put("KFC", "kfc");
map.put("WNBA", "wnba");
map.put("NBA", "nba");
map.put("CBA", "cba");

Map<String, String> collect = map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) //倒序
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oleValue, newValue) -> oleValue, LinkedHashMap::new));

        System.out.println(collect);

最终输出:

按value排序

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

        map.put("KFC", "kfc");
        map.put("WNBA", "wnba");
        map.put("NBA", "nba");
        map.put("CBA", "cba");

        Map<String, String> collect = map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue()) //正序
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oleValue, newValue) -> oleValue, LinkedHashMap::new));

        System.out.println(collect);

最终输出:

很多写法在java8以上都简化了,很方便

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~