Backend Development 6 min read

Using Java 8 Map.merge() to Aggregate Student Scores

This article introduces Java 8's Map.merge() method, demonstrates how to replace verbose map‑update code with a concise merge operation for summing student scores, explains the underlying mechanism, and briefly mentions related map utilities such as compute and putIfAbsent.

Architect's Tech Stack
Architect's Tech Stack
Architect's Tech Stack
Using Java 8 Map.merge() to Aggregate Student Scores

Java 8 brings many functional‑programming features, such as lambda expressions, and introduces useful methods for the Map interface, among which Map.merge() simplifies common aggregation tasks.

The article starts with a concrete example: a list of StudentScore objects, each containing a student name, a subject, and a score, and the goal is to compute the total score for each student.

private List
buildATestList() {
    List
studentScoreList = new ArrayList<>();
    StudentScore studentScore1 = new StudentScore() {{
        setStuName("张三");
        setSubject("语文");
        setScore(70);
    }};
    // ... (similar objects for other subjects and students) ...
    studentScoreList.add(studentScore1);
    // add the rest of the objects
    return studentScoreList;
}

First, the conventional approach uses forEach to check whether a key already exists in the map and updates the value manually:

ObjectMapper objectMapper = new ObjectMapper();
List
studentScoreList = buildATestList();
Map
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));
// Result: {"李四":228,"张三":215,"王五":235}

Using Map.merge() the same logic becomes a single line:

Map
studentScoreMap2 = new HashMap<>();
studentScoreList.forEach(studentScore ->
    studentScoreMap2.merge(
        studentScore.getStuName(),
        studentScore.getScore(),
        Integer::sum));
System.out.println(objectMapper.writeValueAsString(studentScoreMap2));
// Result: {"李四":228,"张三":215,"王五":235}

The merge method has the signature default V merge(K key, V value, BiFunction remappingFunction) . If the key is absent, it behaves like put(key, value) ; otherwise it applies the provided remapping function (e.g., Integer::sum ) to combine the existing and new values.

This behavior makes merge especially useful for grouping and summing operations, offering a cleaner alternative to manual checks when processing collections.

The article also mentions other useful Map methods introduced in Java 8, such as putIfAbsent , compute() , computeIfAbsent() , and computeIfPresent() , and provides the source of compute() for reference.

In conclusion, Map.merge() provides a concise and readable way to aggregate map values, and understanding its source helps developers apply it correctly in real‑world scenarios.

backendJavaCollectionsJava8FunctionalProgrammingMap.merge
Architect's Tech Stack
Written by

Architect's Tech Stack

Java backend, microservices, distributed systems, containerized programming, and more.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.