JDK 1.8 之 Map.merge()

MapConcurrentHashMap是线程安全的,但不是全部操做都是,例如get()以后再put()就不是了,这时使用merge()确保没有更新会丢失。java

由于Map.merge()意味着咱们能够原子地执行插入或更新操做,它是线程安全的。git

1、源码解析

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 能够选择合并的方式:github

  1. 只返回新值便可覆盖旧值: (old, new) -> new;
  2. 只需返回旧值便可保留旧值:(old, new) -> old;
  3. 合并二者,例如:(old, new) -> old + new;
  4. 删除旧值:(old, new) -> null

2、使用场景

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)app

  1. Map中不存在指定的key时,将传入的value设置为key的值;
  2. 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
复制代码
  • 结果小结
  1. merger()方法使用起来在必定程度上减小了代码量,使得代码更加简洁。同时,经过打印的方法耗时能够看出,merge()方法效率更高。
  2. Map.merge()的出现,和ConcurrentHashMap的结合,完美处理那些自动执行插入或者更新操做的单线程安全的逻辑.

3、总结

3.1 示例源码

Github 示例代码ui

3.2 技术交流

  1. 风尘博客
  2. 风尘博客-博客园
  3. 风尘博客-CSDN

关注公众号,了解更多:spa

风尘博客
相关文章
相关标签/搜索