toMap() with Merge Function: Resolving Conflicts
What you'll learn: How to use a merge function with toMap() to control what happens when duplicate keys collide during stream collection.
The Problem with Duplicate Keys
When you learned about handling duplicate keys in toMap(), you saw that duplicates throw an IllegalStateException by default. But what if you want to handle duplicates intelligently—keeping the first value, preferring the last, or even combining them?
The Three-Argument toMap()
The toMap() collector accepts a third argument: a merge function. This BinaryOperator tells the collector how to resolve conflicts when two stream elements map to the same key.
Collectors.toMap(
keyMapper,
valueMapper,
mergeFunction // (oldValue, newValue) -> resolvedValue
)
Common Merge Strategies
Keep the first value:
Map<String, Integer> map = stream.collect(
Collectors.toMap(
Person::getName,
Person::getAge,
(existing, replacement) -> existing // keep first
)
);
Keep the last value:
(existing, replacement) -> replacement // overwrite with latest
Combine values (e.g., sum ages):
(age1, age2) -> age1 + age2 // add them together
Real-World Analogy
Think of it like a filing system where multiple documents might belong to the same folder. The merge function is your policy: do you keep the oldest document, replace with the newest, or staple them together?
Key Takeaway:
The merge function in toMap() gives you full control over duplicate key resolution—you can keep the first value, last value, or combine them using any logic you need.