Handling Duplicate Keys in toMap
What you'll learn: How to use the merge function parameter in Collectors.toMap() to handle collisions when multiple stream elements produce the same key.
By default, toMap() throws an IllegalStateException if two elements map to the same key. In real-world scenarios, duplicate keys are common—think of grouping items by category or aggregating values. The solution is to provide a merge function that tells Java how to combine conflicting values.
The Merge Function Parameter
The three-argument form of toMap() accepts a merge function as its third parameter:
Collectors.toMap(keyMapper, valueMapper, mergeFunction)
The merge function takes two values (the existing and new values for the same key) and returns the value to keep.
Common Merge Strategies
Keep the first value:
Map<String, Integer> map = stream.collect(
Collectors.toMap(
Employee::getDepartment,
Employee::getSalary,
(existing, replacement) -> existing
)
);
Keep the last value:
(existing, replacement) -> replacement
Sum the values:
Map<String, Integer> salaryByDept = employees.stream().collect(
Collectors.toMap(
Employee::getDepartment,
Employee::getSalary,
(sal1, sal2) -> sal1 + sal2
)
);
Keep the maximum:
(existing, replacement) -> Math.max(existing, replacement)
Analogy
Think of a merge function like a referee deciding what happens when two people want the same seat: keep the first person, give it to the second, or find a compromise (like sharing or using a bigger seat).
Key Takeaway: When using toMap() with potential duplicate keys, always provide a merge function as the third argument to specify how conflicting values should be resolved—whether by keeping one, combining them, or applying custom logic.