Collectors: groupingBy, partitioningBy, teeing, toUnmodifiableList
The common ways to reshape a stream into something more structured than a flat list. groupingBy buckets
elements by a key into a Map. partitioningBy is the two-bucket special case (always produces exactly a
true/false map, even if one side is empty). teeing runs two collectors over the same stream in a
single pass and combines their results -- useful when you'd otherwise have to iterate twice.
import java.util.*;
import java.util.stream.*;
record Person(String name, String dept, int age) {}
List<Person> people = List.of(
new Person("Amy", "Eng", 30), new Person("Bob", "Eng", 25),
new Person("Cid", "Sales", 40), new Person("Dee", "Sales", 22)
);
Map<String, List<String>> byDept = people.stream()
.collect(Collectors.groupingBy(Person::dept, Collectors.mapping(Person::name, Collectors.toList())));
System.out.println("groupingBy: " + byDept);
Map<Boolean, List<String>> partitioned = people.stream()
.collect(Collectors.partitioningBy(p -> p.age() >= 30, Collectors.mapping(Person::name, Collectors.toList())));
System.out.println("partitioningBy age>=30: " + partitioned);
var result = people.stream().collect(Collectors.teeing(
Collectors.counting(),
Collectors.averagingInt(Person::age),
(count, avgAge) -> "count=" + count + ", avgAge=" + avgAge
));
System.out.println("teeing (two collectors run in one pass, combined): " + result);
List<String> immutableNames = people.stream().map(Person::name).collect(Collectors.toUnmodifiableList());
try {
immutableNames.add("Eve");
} catch (UnsupportedOperationException e) {
System.out.println("toUnmodifiableList() rejects mutation: " + e);
}