Mastery
Mastery/Java/C. Collections framework
T2 · intermediate depth

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.

java
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);
java
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);
}

Interview angle

A practical fluency check: ask a candidate to group a list of objects by a field and count each group — the one-line Collectors.groupingBy(..., Collectors.counting()) answer versus a manual HashMap and a for-loop is a quick, low-drama way to gauge how comfortable someone is with the modern Collectors API versus pre-Java-8 idioms.

In the industry

groupingBy/partitioningBy are the default idiom for reshaping data in any Java codebase written since streams became standard — replacing manual accumulation loops almost entirely for this kind of task. teeing (Java 12+) is newer and less universally known, reached for specifically to avoid iterating a stream twice when two independent aggregations are both needed — a real, measurable efficiency win on large collections that's still catching on in codebases slower to adopt newer Java versions.