源码解析JDK 1.8 中的 Map.merge()
作者:风尘博客 发布时间:2023-11-16 23:49:25
Map 中ConcurrentHashMap是线程安全的,但不是所有操作都是,例如get()之后再put()就不是了,这时使用merge()确保没有更新会丢失。
因为Map.merge()意味着我们可以原子地执行插入或更新操作,它是线程安全的。
一、源码解析
default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
Objects.requireNonNull(remappingFunction);
Objects.requireNonNull(value);
V oldValue = get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if(newValue == null) {
remove(key);
} else {
put(key, newValue);
}
return newValue;
}
该方法接收三个参数,一个 key 值,一个 value,一个 remappingFunction 。如果给定的key不存在,它就变成了put(key, value);但是,如果key已经存在一些值,我们 remappingFunction 可以选择合并的方式:
只返回新值即可覆盖旧值: (old, new) -> new;
只需返回旧值即可保留旧值:(old, new) -> old;
合并两者,例如:(old, new) -> old + new;
删除旧值:(old, new) -> null。
二、使用场景
merge()方法在统计时用的场景比较多,例如:有一个学生成绩对象的列表,对象包含学生姓名、科目、科目分数三个属性,求得每个学生的总成绩。
2.1 准备数据
学生对象StudentEntity.java
@Data
public class StudentEntity {
/**
* 学生姓名
*/
private String studentName;
/**
* 学科
*/
private String subject;
/**
* 分数
*/
private Integer score;
}
学生成绩数据
private List<StudentEntity> buildATestList() {
List<StudentEntity> studentEntityList = new ArrayList<>();
StudentEntity studentEntity1 = new StudentEntity() {{
setStudentName("张三");
setSubject("语文");
setScore(60);
}};
StudentEntity studentEntity2 = new StudentEntity() {{
setStudentName("张三");
setSubject("数学");
setScore(70);
}};
StudentEntity studentEntity3 = new StudentEntity() {{
setStudentName("张三");
setSubject("英语");
setScore(80);
}};
StudentEntity studentEntity4 = new StudentEntity() {{
setStudentName("李四");
setSubject("语文");
setScore(85);
}};
StudentEntity studentEntity5 = new StudentEntity() {{
setStudentName("李四");
setSubject("数学");
setScore(75);
}};
StudentEntity studentEntity6 = new StudentEntity() {{
setStudentName("李四");
setSubject("英语");
setScore(65);
}};
StudentEntity studentEntity7 = new StudentEntity() {{
setStudentName("王五");
setSubject("语文");
setScore(80);
}};
StudentEntity studentEntity8 = new StudentEntity() {{
setStudentName("王五");
setSubject("数学");
setScore(85);
}};
StudentEntity studentEntity9 = new StudentEntity() {{
setStudentName("王五");
setSubject("英语");
setScore(90);
}};
studentEntityList.add(studentEntity1);
studentEntityList.add(studentEntity2);
studentEntityList.add(studentEntity3);
studentEntityList.add(studentEntity4);
studentEntityList.add(studentEntity5);
studentEntityList.add(studentEntity6);
studentEntityList.add(studentEntity7);
studentEntityList.add(studentEntity8);
studentEntityList.add(studentEntity9);
return studentEntityList;
}
2.2 一般方案
思路:用Map的一组key/value存储一个学生的总成绩(学生姓名作为key,总成绩为value)
Map中不存在指定的key时,将传入的value设置为key的值;
当key存在值时,取出存在的值与当前值相加,然后放入Map中。
public void normalMethod() {
Long startTime = System.currentTimeMillis();
// 造一个学生成绩列表
List<StudentEntity> studentEntityList = buildATestList();
Map<String, Integer> studentScore = new HashMap<>();
studentEntityList.forEach(studentEntity -> {
if (studentScore.containsKey(studentEntity.getStudentName())) {
studentScore.put(studentEntity.getStudentName(),
studentScore.get(studentEntity.getStudentName()) + studentEntity.getScore());
} else {
studentScore.put(studentEntity.getStudentName(), studentEntity.getScore());
}
});
log.info("各个学生成绩:{},耗时:{}ms",studentScore, System.currentTimeMillis() - startTime);
}
2.3 Map.merge()
很明显,这里需要采用remappingFunction的合并方式。
public void mergeMethod() {
Long startTime = System.currentTimeMillis();
// 造一个学生成绩列表
List<StudentEntity> studentEntityList = buildATestList();
Map<String, Integer> studentScore = new HashMap<>();
studentEntityList.forEach(studentEntity -> studentScore.merge(
studentEntity.getStudentName(),
studentEntity.getScore(),
Integer::sum));
log.info("各个学生成绩:{},耗时:{}ms",studentScore, System.currentTimeMillis() - startTime);
}
2.4 测试及小结
测试方法
@Test
public void testAll() {
// 一般写法
normalMethod();
// merge()方法
mergeMethod();
}
测试结果
00:21:28.305 [main] INFO cn.van.jdk.eight.map.merge.MapOfMergeTest - 各个学生成绩:{李四=225, 张三=210, 王五=255},耗时:75ms
00:21:28.310 [main] INFO cn.van.jdk.eight.map.merge.MapOfMergeTest - 各个学生成绩:{李四=225, 张三=210, 王五=255},耗时:2ms
结果小结
merger()方法使用起来在一定程度上减少了代码量,使得代码更加简洁。同时,通过打印的方法耗时可以看出,merge()方法效率更高。
Map.merge()的出现,和ConcurrentHashMap的结合,完美处理那些自动执行插入或者更新操作的单线程安全的逻辑.
三、总结
3.1 示例源码
Github 示例代码
总结
以上所述是小编给大家介绍的JDK 1.8 中的 Map.merge(),希望对大家有所帮助。
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
来源:https://www.cnblogs.com/vandusty/archive/2019/10/10/11644487.html


猜你喜欢
- Spring Boot简介SpringBoot为了简化在开发基于 Spring的项目的难度,减少了哪些繁杂的配置,从而让开发基于 Sprin
- 1.引入如下依赖<dependency> <groupId>org.spri
- 一、使用spring initializr创建java工程 1、启动IDEA,新建java工程,使用向导创建一个springboo
- 近期开发收音机有个需求,将频率值以图片的形式显示出来(如结尾效果图所示)。然而,一开始用TextView写出来的效果太丑了,提交上去肯定不合
- 今天就给大家分享android实现支付宝手势密码,很常见,像现在用微信支付,支付宝支付的时候都要自己设置的4位PIN码,然后输入PIN码后立
- 一、RESTful 简介REST 是一种软件架构风格。REST:Representational State Transfer,表现层资源状
- 现在的Android应用,只要有一个什么新的创意,过不了多久,几乎所有的应用都带这个创意。这不,咱们公司最近的一个持续性的项目,想在首页加个
- Java的反射机制允许我们对一个类的加载、实例化、调用方法、操作属性的时期改为在运行期进行,这大大提高了代码的灵活度。但在运行期进行反射操作
- 一、队列的结构队列:一种操作受限的线性表,只允许在线性表的一端进行插入,另一端进行删除,插入的一端称为队尾,删除的一端称为队头通过 动态顺序
- 本文实例讲述了C#用匿名方法定义委托的实现方法。分享给大家供大家参考。具体实现方法如下://用匿名方法定义委托 class Program
- 提要本节继续给大家带来是显示提示信息的第三个控件AlertDialog(对话框),同时它也是其他Dialog的的父类!比如ProgressD
- public void refresh() throws BeansException, IllegalStateException { &
- maven没有打包xml文件的问题最近使用maven带管理项目,采用SSM的技术栈,在配置好一些配置文件,打包部署到tomcat上,出现没有
- 本文实例为大家分享了Android实现支付宝记账饼图,点击旋转到最下面,供大家参考,具体内容如下代码:package com.example
- 通常C#使用基于XML的配置文件,不过如果有需要的话,比如要兼顾较老的系统,可能还是要用到INI文件。但C#本身并不具备读写INI文件的AP
- 前言SQL注入漏洞作为WEB安全的最常见的漏洞之一,在java中随着预编译与各种ORM框架的使用,注入问题也越来越少。新手代码审计者往往对J
- 项目要求1.初次打开程序时右上角标题栏显示“无连接”,点击旁边的按钮选择“我的好友”,进入配对界面;2.选择好友之后,返回主界面,标题栏会显
- 1.SpringBoot整合JDBCTemplate1.1.导入jdbc相关依赖包主要的依赖包:<dependency> &nb
- 1. 前言SpringBoot在包扫描时,并不会扫描子模块下的内容,这样就使得我们的子模块中的Bean无法注入到Spring容器中。Spri
- 要实现摇一摇的功能,类似于微信的摇一摇方法1:通过分析加速计数据来判断是否进行了摇一摇操作(比较复杂)方法2:iOS自带的Shake监控AP