The biggest feature of Java 8 is nothing less than a more functional orientation, such as the introduction of lambda, which makes functional programming easier. Merge () = map.merge() = map.merge() = map.merge() Let’s start with an example.

merge()How does it work?

Suppose we have the following business logic, I have a list of student score objects, the object contains the student name, subject, subject score three attributes, to obtain the total score of each student. Add to the list as follows:

    private List<StudentScore> buildATestList(a) {
        List<StudentScore> studentScoreList = new ArrayList<>();
        StudentScore studentScore1 = new StudentScore() {{
            setStuName("Zhang");
            setSubject("Chinese");
            setScore(70);
        }};
        StudentScore studentScore2 = new StudentScore() {{
            setStuName("Zhang");
            setSubject("Mathematics");
            setScore(80);
        }};
        StudentScore studentScore3 = new StudentScore() {{
            setStuName("Zhang");
            setSubject("English");
            setScore(65);
        }};
        StudentScore studentScore4 = new StudentScore() {{
            setStuName("Bill");
            setSubject("Chinese");
            setScore(68);
        }};
        StudentScore studentScore5 = new StudentScore() {{
            setStuName("Bill");
            setSubject("Mathematics");
            setScore(70);
        }};
        StudentScore studentScore6 = new StudentScore() {{
            setStuName("Bill");
            setSubject("English");
            setScore(90);
        }};
        StudentScore studentScore7 = new StudentScore() {{
            setStuName("Fifty");
            setSubject("Chinese");
            setScore(80);
        }};
        StudentScore studentScore8 = new StudentScore() {{
            setStuName("Fifty");
            setSubject("Mathematics");
            setScore(85);
        }};
        StudentScore studentScore9 = new StudentScore() {{
            setStuName("Fifty");
            setSubject("English");
            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;
    }
Copy the code

Let’s look at the general practice first:

        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));// The result is as follows:
// {" li Si ":228," Zhang SAN ":215," Wang Wu ":235}
Copy the code

Then let’s see how merge() works:

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

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

// The result is as follows:
// {" li Si ":228," Zhang SAN ":215," Wang Wu ":235}
Copy the code

merge()Introduction to the

Merge (), which assigns a new value to the key (if it does not exist) or updates the value corresponding to the given key.

    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;
    }
Copy the code

The method takes three arguments, a key, a value, and a remappingFunction. If the given key does not exist, it becomes PUT (key, value). However, if the key already has some values, we remappingFunction can choose how to merge and then assign the merged newValue to the original key.

Usage scenarios

Merge () is a good option if you want to do something else in the loop, although the stream has the groupingBy() method.

other

In addition to the merge() method, I also saw some other map-related methods in Java 8, such as putIfAbsent, compute(), computeIfAbsent(), computeIfPresent, Compute ()(map.class) returns the new value of the compute()(map.class) method: compute()(map.class);

    default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue = this.get(key);
        V newValue = remappingFunction.apply(key, oldValue);
        if (newValue == null) {
            if (oldValue == null&&!this.containsKey(key)) {
                return null;
            } else {
                this.remove(key);
                return null; }}else {
            this.put(key, newValue);
            returnnewValue; }}Copy the code

conclusion

Merge () : compute(); merge() : TreeNode; merge() : TreeNode; merge() : TreeNode; merge() : TreeNode; Therefore, the source must be to see, do not understand the place to read more practice naturally understand.

link

  • Reference:

    www.jianshu.com/p/68e6b3041…

  • Test code address:

    Github.com/lq920320/al…