JDK 1.8 之 Map.merge()


MapConcurrentHashMap是線程安全的,但不是所有操作都是,例如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 可以選擇合並的方式:

  1. 只返回新值即可覆蓋舊值: (old, new) -> new;
  2. 只需返回舊值即可保留舊值:(old, new) -> old;
  3. 合並兩者,例如:(old, new) -> old + new;
  4. 刪除舊值:(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)

  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.1 示例源碼

Github 示例代碼

3.2 技術交流

  1. 風塵博客
  2. 風塵博客-CSDN
  3. 風塵博客-掘金


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM