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.
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<StudentScore> buildATestList() {
List<StudentScore> 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<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));
// Result: {"李四":228,"张三":215,"王五":235}Using Map.merge() the same logic becomes a single line:
Map<String, Integer> 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<? super V,? super V,? extends V> 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
