码迷,mamicode.com
首页 > 编程语言 > 详细

Stream排序Map集合

时间:2020-01-28 22:58:15      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:https   print   linked   相关   pre   stream   ble   return   out   

最近小编自己一个人在负责一个项目的后台开发,其中有一部分是统计相关的功能,所以需要一些排序或者分组的操作,之前这种操作小编觉得还是比较麻烦的,虽热有一些现成的工具类,但是工具类的写法也是比较复杂的,但是如果使用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

Stream排序Map集合

标签:https   print   linked   相关   pre   stream   ble   return   out   

原文地址:https://www.cnblogs.com/eternityz/p/12238979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!