Nested Grouping: Multi-Level Classification
You'll learn how to chain groupingBy collectors to create nested Maps that classify data at multiple levels simultaneously.
The Core Idea
Sometimes grouping by a single property isn't enough. Imagine organizing a company's employees first by department, then by job level within each department. This is nested grouping: you use one groupingBy collector as the downstream collector of another groupingBy.
The result is a Map<OuterKey, Map<InnerKey, List<Value>>> — essentially a two-dimensional classification structure.
How It Works
You've already seen groupingBy with downstream collectors like counting() or summingInt(). For multi-level grouping, the downstream collector is another groupingBy:
Map<Department, Map<Level, List<Employee>>> result =
employees.stream()
.collect(
Collectors.groupingBy(
Employee::getDepartment, // First level
Collectors.groupingBy(
Employee::getLevel // Second level
)
)
);
Reading the Result
The outer Map's keys are departments. Each value is itself a Map where keys are job levels, and values are lists of employees. To access "all Senior engineers in Engineering":
List<Employee> seniorEngineers = result
.get(Department.ENGINEERING)
.get(Level.SENIOR);
Beyond Two Levels
You can nest even deeper by adding more groupingBy layers, though readability suffers. Three-level grouping creates Map<A, Map<B, Map<C, List<D>>>>.
Key Takeaway: Chain groupingBy collectors to create nested Maps for multi-level classification — the downstream collector of one groupingBy can be another groupingBy, producing hierarchical data structures like Map<Outer, Map<Inner, List<Value>>>.