library
intermediateCollectors: toMap, groupingBy, partitioningBy
Master the essential Collectors for stream terminal operations and avoid common pitfalls with toMap.
The Collectors class provides factory methods for common stream reduction operations.
Collectors = different sorting machines at the end of an assembly line. toList() = dump everything into one bin. groupingBy = sort into labeled bins. toMap = stick a label on each item and file it.
Key Concepts
1
Key collectors:
2
1. toList(), toSet(), toUnmodifiableList(): basic collection.
3
2. toMap(keyMapper, valueMapper): creates a Map.
PITFALL: throws IllegalStateException on duplicate keys! Always provide a merge function.
toMap(k, v, (v1, v2) -> v1) — keep first on duplicate.
4
3. groupingBy(classifier): groups elements by a key → Map<K, List<V>>.
Two-arg: groupingBy(classifier, downstream) — apply a downstream collector to each group.
Example: groupingBy(dept, counting()) → Map<String, Long>
5
4. partitioningBy(predicate): splits into true/false groups → Map<Boolean, List<V>>.
Special case of groupingBy with exactly two groups.
6
5. joining(delimiter, prefix, suffix): concatenate strings.
7
6. Downstream collectors for groupingBy:
- counting(): count per group
- summingInt/Long/Double: sum per group
- averagingInt/Long/Double: average per group
- maxBy/minBy: find max/min per group
- mapping: transform then collect
- reducing: custom reduction per group
- collectingAndThen: post-process the result
8
7. Custom collector: Collector.of(supplier, accumulator, combiner, finisher, characteristics).