怎么在java8中使用stream 操作map

发布时间:2021-06-04 17:16:14 作者:Leah
来源:亿速云 阅读:334

这篇文章给大家介绍怎么在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;
  }

关于怎么在java8中使用stream 操作map就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Java8中Stream API的应用
  2. java8中Stream的使用示例教程

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java8 map key

上一篇:怎么在SpringBoot中实现并发定时任务

下一篇:怎么在springcloud微服务中利用redis集群实现单点登录

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》