Mastering Java 8’s Map.merge(): Simplify Grouped Summations
This article explains Java 8’s Map.merge() method, demonstrating how to replace traditional looping logic with concise functional code to aggregate student scores, includes full code examples, compares it with conventional approaches, and discusses related map methods and practical use cases.
Java 8’s biggest feature is functional programming support such as lambda and new collection methods. This article introduces Map.merge() and shows how to use it.
How to use merge()
Assume we have a list of StudentScore objects with fields name, subject, score, and we want to calculate each student’s total score.
private List<StudentScore> buildATestList() {
List<StudentScore> studentScoreList = new ArrayList<>();
StudentScore studentScore1 = new StudentScore(){{
setStuName("张三");
setSubject("语文");
setScore(70);
}};
// ... other students ...
studentScoreList.add(studentScore1);
// ... add others ...
return studentScoreList;
}Traditional approach using forEach and manual map updates:
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));
// {"李四":228,"张三":215,"王五":235}Using Map.merge():
Map<String, Integer> studentScoreMap2 = new HashMap<>();
studentScoreList.forEach(studentScore -> studentScoreMap2.merge(
studentScore.getStuName(),
studentScore.getScore(),
Integer::sum));
System.out.println(objectMapper.writeValueAsString(studentScoreMap2));
// {"李四":228,"张三":215,"王五":235}merge() Overview
merge() assigns a new value to a key if the key does not exist, or updates the existing value using a remapping function. Its signature is:
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;
}The method takes a key, a value, and a remapping function. If the key is absent, it behaves like put(key, value); otherwise the remapping function determines how to combine the old and new values.
Use Cases
merge() is useful for grouping and summing operations, similar to stream’s groupingBy(), but works well when additional processing is needed inside a loop.
Other Related Methods
Java 8 also provides other map methods such as putIfAbsent, compute, computeIfAbsent, computeIfPresent, etc. For example, compute() is defined as:
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);
return newValue;
}
}Conclusion
The article introduced Map.merge() for aggregating values in a map, noted that HashMap’s implementation relies on TreeNode and red‑black trees, and mentioned that similar principles apply to compute() and other related methods. Reading the source code helps deepen understanding.
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
