源码解析JDK 1.8 中的 Map.merge()

 更新时间:2019年10月10日 10:06:28   作者:风尘博客  
这篇文章主要介绍了JDK 1.8 之 Map.merge()的相关知识,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

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(),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

  • Java数据结构常见几大排序梳理

    Java数据结构常见几大排序梳理

    Java常见的排序算法有:直接插入排序、希尔排序、选择排序、冒泡排序、归并排序、快速排序、堆排序等。本文详解介绍它们的实现以及图解,需要的可以参考一下
    2022-03-03
  • Java 多线程死锁的产生以及如何避免死锁

    Java 多线程死锁的产生以及如何避免死锁

    这篇文章主要介绍了Java 多线程死锁的产生以及如何避免死锁,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-09-09
  • Java如何实现读取txt文件内容并生成Word文档

    Java如何实现读取txt文件内容并生成Word文档

    本文主要介绍了通过Java实现读取txt文件中的内容,并将内容生成Word文档。文章的代码非常详细,具有一定的学习价值,感兴趣的小伙伴可以了解一下
    2021-12-12
  • Java集合的定义与Collection类使用详解

    Java集合的定义与Collection类使用详解

    这篇文章主要介绍了Java集合的定义及Collection工具类使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2022-11-11
  • Java随机数的5种获得方法(非常详细!)

    Java随机数的5种获得方法(非常详细!)

    这篇文章主要给大家介绍了关于Java随机数的5种获得方法,在实际开发中产生随机数的使用是很普遍的,所以在程序中进行产生随机数操作很重要,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2023-10-10
  • Spring存储与读取Bean对象方法

    Spring存储与读取Bean对象方法

    在Spring中,要想更简单的存储和读取对象的核心是使用注解,这篇文章主要给大家介绍了关于Spring如何通过注解存储和读取对象的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-01-01
  • java中调用super的实例讲解

    java中调用super的实例讲解

    在本篇文章里小编给大家分享了一篇关于java中调用super的实例讲解内容,有兴趣的朋友们可以学习下。
    2020-12-12
  • 接口签名怎么用Java实现

    接口签名怎么用Java实现

    今天带大家学习java的相关知识,文章围绕怎么用Java实现接口签名展开,文中有非常详细的代码示例及介绍,需要的朋友可以参考下
    2021-06-06
  • 浅谈Java中向上造型向下造型和接口回调中的问题

    浅谈Java中向上造型向下造型和接口回调中的问题

    这篇文章主要介绍了浅谈Java中向上造型向下造型和接口回调中的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • Java中的MapStruct用法详解

    Java中的MapStruct用法详解

    这篇文章主要介绍了Java中的MapStruct用法详解,MapStuct的使用非常简单,把对应的jar包引入即可,本文通过示例代码给大家介绍的非常详细,需要的朋友可以参考下
    2022-04-04

最新评论