給老弟講解java8中的marge()方法,一頓騷操作

今天我弟弟在家里學(xué)習(xí)java的時候問我java8特性中的map.merge()方法,當(dāng)時剛下班回來,準(zhǔn)備洗個澡回來就睡的,但是我覺得這個還是很好用的,所以還是給他詳細說了一下。畢竟學(xué)習(xí)這么努力,我也不好打擊他嘛。

merge() 怎么用?

這么跟你說吧。

假設(shè)我們有這么一段業(yè)務(wù)邏輯,我有一個學(xué)生成績對象的列表,對象包含學(xué)生姓名、科目、科目分?jǐn)?shù)三個屬性,要求求得每個學(xué)生的總成績。加入列表如下:

private List<StudentScore> buildATestList() {
        List<StudentScore> studentScoreList = new ArrayList<>();
        StudentScore studentScore1 = new StudentScore() {{
            setStuName("張三");
            setSubject("語文");
            setScore(70);
        }};
        StudentScore studentScore2 = new StudentScore() {{
            setStuName("張三");
            setSubject("數(shù)學(xué)");
            setScore(80);
        }};
        StudentScore studentScore3 = new StudentScore() {{
            setStuName("張三");
            setSubject("英語");
            setScore(65);
        }};
        StudentScore studentScore4 = new StudentScore() {{
            setStuName("李四");
            setSubject("語文");
            setScore(68);
        }};
        StudentScore studentScore5 = new StudentScore() {{
            setStuName("李四");
            setSubject("數(shù)學(xué)");
            setScore(70);
        }};
        StudentScore studentScore6 = new StudentScore() {{
            setStuName("李四");
            setSubject("英語");
            setScore(90);
        }};
        StudentScore studentScore7 = new StudentScore() {{
            setStuName("王五");
            setSubject("語文");
            setScore(80);
        }};
        StudentScore studentScore8 = new StudentScore() {{
            setStuName("王五");
            setSubject("數(shù)學(xué)");
            setScore(85);
        }};
        StudentScore studentScore9 = new StudentScore() {{
            setStuName("王五");
            setSubject("英語");
            setScore(70);
        }};

        studentScoreList.add(studentScore1);
        studentScoreList.add(studentScore2);
        studentScoreList.add(studentScore3);
        studentScoreList.add(studentScore4);
        studentScoreList.add(studentScore5);
        studentScoreList.add(studentScore6);
        studentScoreList.add(studentScore7);
        studentScoreList.add(studentScore8);
        studentScoreList.add(studentScore9);

        return studentScoreList;
    }

我們先看一下常規(guī)做法:

  ObjectMapper objectMapper = new ObjectMapper();
        List<StudentScore> studentScoreList = buildATestList();

        Map<String, Integer> studentScoreMap = new HashMap<>();
        studentScoreList.forEach(studentScore -> {
            if (studentScoreMap.containsKey(studentScore.getStuName())) {
                studentScoreMap.put(studentScore.getStuName(), 
                                    studentScoreMap.get(studentScore.getStuName()) + studentScore.getScore());
            } else {
                studentScoreMap.put(studentScore.getStuName(), studentScore.getScore());
            }
        });

        System.out.println(objectMapper.writeValueAsString(studentScoreMap));

// 結(jié)果如下:
// {"李四":228,"張三":215,"王五":235}

然后再看一下 merge() 是怎么做的:

      Map<String, Integer> studentScoreMap2 = new HashMap<>();
        studentScoreList.forEach(studentScore -> studentScoreMap2.merge(
          studentScore.getStuName(),
          studentScore.getScore(),
          Integer::sum));

        System.out.println(objectMapper.writeValueAsString(studentScoreMap2));

// 結(jié)果如下:
// {"李四":228,"張三":215,"王五":235}

merge() 簡介

merge() 可以這么理解:它將新的值賦值到 key (如果不存在)或更新給定的key 值對應(yīng)的 value,其源碼如下:

 default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        Objects.requireNonNull(value);
        V oldValue = this.get(key);
        V newValue = oldValue == null ? value : remappingFunction.apply(oldValue, value);
        if (newValue == null) {
            this.remove(key);
        } else {
            this.put(key, newValue);
        }

        return newValue;
    }

我們可以看到原理也是很簡單的,該方法接收三個參數(shù),一個 key 值,一個 value,一個 remappingFunction ,如果給定的key不存在,它就變成了 put(key, value) 。但是,如果 key 已經(jīng)存在一些值,我們 remappingFunction 可以選擇合并的方式,然后將合并得到的 newValue 賦值給原先的 key。

使用場景

好的,我們在看看使用場景,這個使用場景相對來說還是比較多的,比如分組求和這類的操作,雖然 stream 中有相關(guān) groupingBy() 方法,但如果你想在循環(huán)中做一些其他操作的時候,merge() 還是一個挺不錯的選擇的。

其他

然后給你在擴展幾個方法吧(越講越興奮)除了 merge() 方法之外,Java 8 中 map 相關(guān)的其他方法,比如 putIfAbsent 、compute() 、computeIfAbsent() 、computeIfPresent,這些方法看名字應(yīng)該就知道是什么意思了,感興趣的可以簡單閱讀一下源碼(都還是挺易懂的)。行了,我洗個澡就去睡了,明天還要上班。然后叫老弟把這些看了自己也去睡呀,沒看完就不要睡呀。

對了,小編為大家準(zhǔn)備了一套2020最新的web前端資料,需要點擊下方鏈接獲取方式

學(xué)習(xí)前端,你掌握這些。二線也能輕松拿8K以上

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容