Collectors and grouping
What you will learn
Collectors combine stream elements into structures such as lists, maps or summary values. A collector defines how to start a result container, add elements, merge partial containers, and optionally finish the result. Use grouping to summarize records by a key and partitioning to separate two outcomes.
- Choose groupingBy, partitioningBy or joining for a report.
- Specify a duplicate-key policy for toMap.
- Distinguish collector output guarantees from observed implementation choices.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Group by category and sum units
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { record Stock(String category, int units) {} var stock = List.of(new Stock("paper", 4), new Stock("tools", 2), new Stock("paper", 6)); var totals = stock.stream().collect(Collectors.groupingBy(Stock::category, TreeMap::new, Collectors.summingInt(Stock::units))); System.out.println(totals); }}Expected output:
{paper=10, tools=2}The classifier chooses a key; summingInt produces the per-category total. TreeMap supplies key order.
Choose a result container
Stream.toList() is unmodifiable. Collectors.toList() does not specify the concrete list type or mutability; request Collectors.toCollection(ArrayList::new) when a mutable ArrayList is part of the contract. joining(delimiter) combines character sequences in encounter order. A collector uses supplier, accumulator, combiner and finisher; IDENTITY_FINISH indicates the accumulated container can serve as the result, UNORDERED means encounter order is not required for equivalence, and CONCURRENT permits concurrent accumulation under its contract.
Classify and summarize
groupingBy(classifier) groups values into lists keyed by the classifier. A downstream collector such as summingInt, counting or mapping changes the result for each group. Use the map-factory overload if output key order matters. partitioningBy(predicate) always provides true and false keys, even when one side has no items. It does not specify the map implementation. Avoid null group keys in these examples; explicitly classify missing data before grouping.
Resolve duplicate keys deliberately
toMap(keyMapper, valueMapper) rejects duplicate mapped keys with IllegalStateException. The merge-function overload specifies how to resolve a collision; choose sum for additive counts, or reject duplicates if they violate a business invariant. The map-factory overload lets you choose a TreeMap or LinkedHashMap. Do not depend on default map iteration order. mapping transforms elements before a downstream reduction.
Partition even when a group is empty
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { var parts = Stream.of(4, 8).collect(Collectors.partitioningBy(n -> n > 0)); System.out.println(parts.get(true)); System.out.println(parts.get(false)); }}Expected output:
[4, 8][]Both boolean keys exist, including the empty false partition.
Resolve repeated product codes
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { record Line(String code, int units) {} var lines = List.of(new Line("B", 2), new Line("A", 3), new Line("B", 5)); Map<String, Integer> totals = lines.stream().collect(Collectors.toMap(Line::code, Line::units, Integer::sum, TreeMap::new)); System.out.println(totals); }}Expected output:
{A=3, B=7}The two B quantities are added, rather than silently replaced.
Map names inside groups and join labels
import java.util.*;import java.util.stream.*;public class Main { public static void main(String[] args) { record Person(String team, String name) {} var people = List.of(new Person("red", "Ada"), new Person("red", "Bo"), new Person("blue", "Cy")); var labels = people.stream().collect(Collectors.groupingBy(Person::team, TreeMap::new, Collectors.mapping(Person::name, Collectors.joining(" / ")))); System.out.println(labels); var mutable = people.stream().map(Person::name).collect(Collectors.toCollection(ArrayList::new)); mutable.add("Dee"); System.out.println(mutable); }}Expected output:
{blue=Cy, red=Ada / Bo}[Ada, Bo, Cy, Dee]Downstream mapping extracts names before joining; the explicit collection factory permits adding an element.
Common mistakes
Do not assume groupingBy sorts its keys or that Collectors.toList guarantees an ArrayList. Pick an explicit map or collection factory when an external contract requires an order or mutation.
Practice
Group the labels ["ink", "pen", "ink", "pad"] by the first character and count each group, using a TreeMap. Print the map. Then partition the original labels by whether they equal "ink" and print both partition sizes (true then false).
Expected output:
{i=2, p=2}22Compare your answer with the manual practice criteria.
Official reading: Java SE 25 Stream API · Stream package contracts · Collectors. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Collectors and grouping — knowledge check
Original Java stream contract and boundary questions. Java 21-compatible scope.
Which collector returns a map with both boolean keys?
What happens to duplicate keys in the two-argument toMap?
Which collection factory guarantees a mutable ArrayList?
How do you request sorted group keys?
What does mapping(Person::name, joining(",")) do downstream?