专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

Stream排序Map集合

最近小编自己一个人在负责一个项目的后台开发,其中有一部分是统计相关的功能,所以需要一些排序或者分组的操作,之前这种操作小编觉得还是比较麻烦的,虽热有一些现成的工具类,但是工具类的写法也是比较复杂的,但是如果使用java8 stream流的话就比较简单了,并且代码量会大大的减少,下面总结几个对map的操作。

1、map 根据value排序

Map<String,BigDecimal> map =new HashMap<>();
map.put("one", 0.08);
map.put("two", 0.1);
map.put("three", 0.2);
map.put("four", 0.91);

上面是项目中的一个中间结果,我们需要对这个map根据value值倒序排序,下面给出工具类:

public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();

    map.entrySet().stream()
            .sorted(Map.Entry.<K, V>comparingByValue()
                    .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
}

当然如果我们想根据map的key进行排序,需要对上面的工具类进行小小的修改,代码如下:

public , V > Map<K, V> sortByKey(Map<K, V> map) {
Map<K, V> result = new LinkedHashMap<>();

    map.entrySet().stream()
            .sorted(Map.Entry.<K, V>comparingByKey()
                    .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
}

我们可以看到,如果我们需要根据key排序,就需要让key 继承 Comparable ,也就说我们需要对待排序的字段继承 Comparable接口。另一个问题就是,上面的这种写法排序效果是 降序排序,如果我们需要升序排序的话,只需要将上面的.reversed()关键字限制去掉即可。

public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
Map<K, V> result = new LinkedHashMap<>();

    map.entrySet().stream()
            .sorted(Map.Entry.<K, V>comparingByValue()
                    ).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
}

map根据value倒序排序

map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).forEach(System.out::println);

map根据key倒序排序

map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).forEach(System.out::println);

map根据value正序排序

map.entrySet().stream().sorted(Comparator.comparing(e -> e.getValue())).forEach(System.out::println);

map根据key正序排序

map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey())).forEach(System.out::println);

参考

链接:https://blog.csdn.net/hao134838/article/details/80780622
链接:https://blog.csdn.net/qq_41011894/article/details/88405944

文章永久链接:https://tech.souyunku.com/46166

未经允许不得转载:搜云库技术团队 » Stream排序Map集合

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们