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

風塵博客
相關文章
相關標籤/搜索