Java Stream Collectors — groupingBy, partitioningBy, toMap
Fast recall
Quick revision
Core answer
Whether you can use collectors beyond toList() — grouping, partitioning, and map conversion are commonly asked in coding interviews
Using toMap() without a merge function and hitting IllegalStateException on duplicate keys
Show nested downstream collectors like groupingBy with counting(), demonstrate toMap with merge functions
Interview-ready guide
Interview answer
Collectors turn a stream pipeline into a concrete data structure — list, map, grouped summary. The basic ones are simple; the production bugs live in toMap() and groupingBy().
toMap():
- Throws
IllegalStateExceptionon duplicate keys by default — a runtime crash that only appears with real data - Fix: provide a merge function —
toMap(Order::getId, identity(), (a, b) -> b)keeps the last entry - Fourth argument controls Map type:
toMap(k, v, merge, LinkedHashMap::new)for insertion order
groupingBy():
- Stream equivalent of SQL
GROUP BY - Default downstream collector is
List— replace withcounting(),summingInt(), or nestedgroupingBy()for aggregation groupingBy(Order::getStatus, counting())gives a frequency map in one line
Gotchas:
- Java 16's
Stream.toList()returns unmodifiable;Collectors.toList()returns mutableArrayList— switching breaks code that modifies the result partitioningBy()always returns bothtrueandfalsekeys, unlikegroupingBy()which omits empty groups
I recommend always providing a merge function with toMap() — even if you think duplicates are impossible; defensive code doesn't crash when assumptions are wrong.
Java Stream Collectors — groupingBy, partitioningBy, toMap
Direct Answer
Collectors are terminal operations that accumulate stream elements into a result container. groupingBy() groups elements by a classifier into a Map<K, List<V>>. partitioningBy() splits into exactly two groups (true/false) using a Predicate. toMap() converts elements into a Map with explicit key and value mappers.
Common Mistakes & Pitfalls
Using toMap() without a merge function and hitting IllegalStateException on duplicate keys
Check your understanding
Answer these without looking back at the article.
- How do you create a custom Collector?
- What is Collectors.teeing() and when would you use it?
- How do collectors work with parallel streams?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.