Lesson · Stream API
Collectors: building maps, lists and strings
14 min readCollectors
A collector is the recipe collect uses to build its result: which container, how elements enter it, and what shape comes out. group, partition and toMap are the ones that turn pipelines into data structures.
What a collector actually is
collect(collector) runs a three-part recipe: a supplier creates the result container, an accumulator puts one element into it, and a combiner merges two containers when work is split across threads. A downstream collector can slot into another collector, which is how groupingBy(team, counting()) works.
The practical consequence: as long as a shape can be described by supplier, accumulator and combiner, there is or can be a collector for it. And because the combiner merges, collectors work unchanged in parallel pipelines.
The catalog you actually reach for
toList, toSet and toCollection cover plain containers. The interesting half of the library is the group of collectors that change the shape of the data.
| Collector | Builds | Typical use |
|---|---|---|
| toList() / toSet() | List / Set | plain containers, deduplication |
| toCollection(TreeSet::new) | any Collection | sorted or custom containers |
| joining(sep, prefix, suffix) | String | display and reports |
| groupingBy(fn) | Map<K, List<T>> | group without losing elements |
| groupingBy(fn, downstream) | Map<K, shape> | count, join or reshape per group |
| partitioningBy(p) | Map<Boolean, List<T>> | exactly two buckets |
| toMap(keyFn, valueFn[, merge]) | Map<K, V> | lookup tables; merge resolves duplicates |
Collector factory · one stream, different shapes
4 players, 2 teamsblue=2 red=2
downstream collector reshapes in the same pass: no lists are built at all
groupingBy is downstream-composable
groupingBy(classifier) alone gives Map<K, List<T>>: keys from the classifier, values as lists. The two-argument form takes a downstream collector, and this is where it shines: counting() gives one number per group, mapping(name, joining()) gives a display string per group, and passing TreeMap::new before the downstream collector even fixes the map kind.
That structure, classifier then downstream, means grouping and computation happen in a single pass: no building a map of lists and then iterating it again.
players.stream().collect(Collectors.groupingBy( Player::team, // key TreeMap::new, // map supplier Collectors.mapping(Player::name, // downstream: reshape each group Collectors.joining(" & "))));
Partitioning: exactly two buckets
partitioningBy is grouping with a boolean key and a guarantee grouping cannot give: both buckets always exist. Grouping produces no entry for a group that never occurs; partitioning always has a true and a false key, even when one side is empty.
When the question is really pass/fail, in/out, above/below, partitioningBy keeps that twofold nature visible instead of leaving a sparse map with one key.
toMap and the duplicate-key collision
toMap(keyFn, valueFn) turns elements into entries. The catch: two elements mapping to the same key throw IllegalStateException, not overwrite. The exception is the API insisting you decide the policy: pass a merge function and the decision becomes explicit, Integer::max keeps the best, (a, b) -> a keeps the first.
Passing the identity merge (a, b) -> b is 'last one wins', which is sometimes genuinely wanted, but the point is that the call site now says so out loud.
Read a collector call as a sentence: groupingBy(team, counting()) is 'group by team, count each group'. If the sentence is awkward, a plain loop may be the better author.
Duplicates are a decision, not a bug
The moment toMap throws 'Duplicate key', the data has said it contains collisions and the code has not said what to do about them. Add the merge function that matches the intent (max, first, last, concatenate) and the crash becomes a documented policy.
Interview angles
What three roles does a Collector define?+
Supplier (create the result container), accumulator (add one element), combiner (merge two containers, used when work is split). Some collectors also define a finisher that transforms the container into the final result shape.
Difference between groupingBy team and counting, versus grouping by team as lists?+
groupingBy(team) builds Map<K, List<T>> holding every element; groupingBy(team, counting()) counts in one pass and never materializes the lists. Same traversal, less memory, sharper result, choose by what the caller needs.
When is partitioningBy better than groupingBy?+
When the key is a single predicate and both outcomes matter: partition always returns both true and false entries, even empty, while grouping omits groups that occur zero times. It documents the twofold split in the type.
Why does toMap throw on duplicate keys by default?+
Because silently keeping one of two values is a data-loss decision the API refuses to make for you. Passing a merge function makes the policy explicit: max, first, last or a combination you define.
How do collectors behave in parallel streams?+
Each worker builds its own container and the combiner merges them, so collectors are parallel-safe by construction. That is why collect, not forEach with a shared list, is the correct accumulation in a parallel pipeline.