Java 8 中 Map 骚操作之 merge() 的用法分析

Java 8 最大的特性无异于更多地面向函数,比如引入了  lambda  等,可以更好地进行函数式编程。前段时间无意间发现了  map.merge()  方法,感觉还是很好用的,此文简单做一些相关介绍。首先我们先看一个例 子。

merge()怎么用

假设我们有这么一段业务逻辑,我有一个学生成绩对象的列表,对象包含学生姓名、科目、科目分数三个属性,要求求得每个学生的总成绩。加入列表如下:

1 private List<StudentScore> buildATestList() { List<StudentScore> studentScoreList = new ArrayList<>(); StudentScore studentScore1 = new StudentScore() {{ setStuName("张三"); setSubject("语文"); setScore(70); }}; StudentScore studentScore2 = new StudentScore() {{ setStuName("张三"); setSubject("数学"); setScore(80); }}; StudentScore studentScore3 = new StudentScore() {{ setStuName("张三"); setSubject("英语"); setScore(65); }}; StudentScore studentScore4 = new StudentScore() {{ setStuName("李四"); setSubject("语文"); setScore(68); }}; StudentScore studentScore5 = new StudentScore() {{ setStuName("李四"); setSubject("数学"); setScore(70); }}; StudentScore studentScore6 = new StudentScore() {{ setStuName("李四"); setSubject("英语"); setScore(90); }}; StudentScore studentScore7 = new StudentScore() {{ setStuName("王五"); setSubject("语文"); setScore(80); }}; StudentScore studentScore8 = new StudentScore() {{ setStuName("王五"); setSubject("数学"); setScore(85); }}; StudentScore studentScore9 = new StudentScore() {{ setStuName("王五"); setSubject("英语"); setScore(70); }}; studentScoreList.add(studentScore1); studentScoreList.add(studentScore2); studentScoreList.add(studentScore3); studentScoreList.add(studentScore4); studentScoreList.add(studentScore5); studentScoreList.add(studentScore6); studentScoreList.add(studentScore7); studentScoreList.add(studentScore8); studentScoreList.add(studentScore9); return studentScoreList;} 2 3 4 5 6

我们先看一下常规做法:

1 ObjectMapper objectMapper = new ObjectMapper();List<StudentScore> studentScoreList = buildATestList();Map<String, Integer> studentScoreMap = new HashMap<>();studentScoreList.forEach(studentScore -> { if (studentScoreMap.containsKey(studentScore.getStuName())) { studentScoreMap.put(studentScore.getStuName(), studentScoreMap.get(studentScore.getStuName()) + studentScore.getScore()); } else { studentScoreMap.put(studentScore.getStuName(), studentScore.getScore()); }});System.out.println(objectMapper.writeValueAsString(studentScoreMap));// 结果如下:// {"李四":228,"张三":215,"王五":235} 2 3 4 5 6

然后再看一下 merge() 是怎么做的:

1 Map<String, Integer> studentScoreMap2 = new HashMap<>();studentScoreList.forEach(studentScore -> studentScoreMap2.merge( studentScore.getStuName(), studentScore.getScore(), Integer::sum));System.out.println(objectMapper.writeValueAsString(studentScoreMap2));// 结果如下:// {"李四":228,"张三":215,"王五":235} 2 3 4 5 6

merge()简介

merge() 可以这么理解:它将新的值赋值到 key (如果不存在)或更新给定的key 值对应的 value,其源码如下:

1 default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); Objects.requireNonNull(value); V oldValue = this.get(key); V newValue = oldValue == null ? value : remappingFunction.apply(oldValue, value); if (newValue == null) { this.remove(key); } else { this.put(key, newValue); } return newValue;} 2 3 4 5 6

我们可以看到原理也是很简单的,该方法接收三个参数,一个 key 值,一个 value,一个 remappingFunction ,如果给定的 key 不存在,它就变成了 put(key, value)。 但是,如果 key 已经存在一些值,我们 remappingFunction 可以选择合并的方式,然后将合并得到的 newValue 赋值给原先的 key。

使用场景

这个使用场景相对来说还是比较多的,比如分组求和这类的操作,虽然 stream 中有相关 groupingBy() 方法,但如果你想在循环中做一些其他操作的时候,merge() 还是一个挺不错的选择的。

其他

除了 merge() 方法之外,我还看到了一些Java 8 中 map 相关的其他方法,比如

putIfAbsent 、compute() 、computeIfAbsent() 、computeIfPresent

这些方法我们看名字应该就知道是什么意思了,故此处就不做过多介绍了,感兴趣的可以简单阅读一下源码(都还是挺易懂的),这里我们贴一下 compute()(Map.class) 的源码,其返回值是计算后得到的新值:

1 default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); V oldValue = this.get(key); V newValue = remappingFunction.apply(key, oldValue); if (newValue == null) { if (oldValue == null && !this.containsKey(key)) { return null; } else { this.remove(key); return null; } } else { this.put(key, newValue); return newValue; }} 2 3 4 5 6

总结

本文简单介绍了一下 Map.merge() 的方法,除此之外,Java 8 中的 HashMap 实现方法使用了 TreeNode 和 红黑树,在源码阅读上可能有一点难度,不过原理上还是相似的,compute() 同理。所以,源码肯定是要看的,不懂的地方多读多练自然就理解了。

作者:LQ木头 
juejin.im/post/5d9b455ae51d45782b0c1bfb

往期精选

Spring中如何使用设计模式,有什么注意事项?

神奇的SQL之层级 → 为什么GROUP BY之后不能直接引用原表中的列

面试若干候选人后,我总结出这份Java面试技巧!

面试官问:你说一说Redis的过期键删除策略

Java 异常处理的 20 个最佳实践,你知道几个?

一文彻底搞懂cookie、session、token,和面试官扯皮就没问题了

美团面试官问Java线程池,这样的回答让他竖起了大拇指!

面试官问:有没有用过分布式锁,是如何实现的?

面试官:这些MQ消息队列问题,在实际面试中我必问!

Java面试高级篇—JavaIO流原理以及Buffered高效原理详解16期

高效开发:IntelliJ IDEA天天用,这些Debug技巧你都知道?

我就知道你“在看”!

本文分享自微信公众号 - Java精选(w_z90110)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java日期时间API系列31

  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前

Java爬虫之JSoup使用教程

title:Java爬虫之JSoup使用教程date:201812248:00:000800update:201812248:00:000800author:mecover:https://imgblog.csdnimg.cn/20181224144920712(https://www.oschin