Stream StormPart 3 of 6
This toMap() Call Crashes Your Java Code (and the Fix) | Stream Storm Part 3
A collector decides the shape of your result. toMap builds a lookup table (and crashes on duplicate keys unless you give it a merge function), partitioningBy splits into exactly two groups, and joining glues strings together.
The toMap crash, and the fix
java
record Score(String name, int score) {}
List<Score> scores = List.of(
new Score("Asha", 82), new Score("Ravi", 45),
new Score("Meena", 67), new Score("Asha", 90));
scores.stream().collect(Collectors.toMap(Score::name, Score::score));
// IllegalStateException: Duplicate key Asha (attempted merging values 82 and 90)
scores.stream().collect(Collectors.toMap(Score::name, Score::score, Math::max));
// {Ravi=45, Asha=90, Meena=67}The third argument is a merge function. It decides what happens when a key repeats; Math::max keeps the higher score.
partitioningBy and joining
java
Collectors.partitioningBy(s -> s.score() >= 50) // always two keys: true and false
Stream.of("Asha", "Ravi", "Meena")
.collect(Collectors.joining(", ", "[", "]")); // [Asha, Ravi, Meena]Read the write-up
- Stream Storm2 min read
Why Collectors.toMap throws "Duplicate key", and how to fix it
toMap refuses to guess which value you want when a key repeats. Give it a merge function and the crash goes away.
Related videos
- Short

- Short
Stream StormJava Streams Explained Visually: filter, map, flatMap, sorted | Stream Storm Part 1
· Part 1 of 6