Stream Storm / Part 3YOUTUBE PLAYER LOADS ON PLAYtoMap() crash, fixed
toMap+partition+collect
This toMap() Call Crashes Your Java Code (and the Fix) | Stream Storm Part 3
In this lesson
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
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
Collectors.partitioningBy(s -> s.score() >= 50) // always two keys: true and false
Stream.of("Asha", "Ravi", "Meena")
.collect(Collectors.joining(", ", "[", "]")); // [Asha, Ravi, Meena]Stream Storm, 9 out
1Java Streams Explained Visually: filter, map, flatMap, sorted1:212Java reduce() and groupingBy() Explained Visually1:373This toMap() Call Crashes Your Java Code (and the Fix)1:504Java Stream anyMatch, findFirst, takeWhile: How Streams Stop Early2:215Java IntStream and mapToInt Explained: The Hidden Boxing Cost1:586Java Parallel Streams Explained: When They Are Faster (and When Not)2:007Find average of numbers in a list0:578Find if element exists in a list using anyMatch()1:009Free Java Streams Interview PDFs (Top 20, 50, 100)0:58Keep going
More Shorts.
Java reduce() and groupingBy() Explained Visually | Stream Storm Part 2, Short.
Java Streams Explained Visually: filter, map, flatMap, sorted | Stream Storm Part 1, Short.
Free Java Streams Interview PDFs (Top 20, 50, 100) | Stream Storm, Short.
Java Parallel Streams Explained: When They Are Faster (and When Not), Short.
