Stream排序Map集合

2020-01-28 16:06:10来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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 <K extends Comparable<? super K>, 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://www.cnblogs.com/eternityz/p/12238979.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:解决浮点运算精度不准确,BigDecimal 加减乘除

下一篇:Spring 事务管理的API