groupingBy: Classifying Elements
Group stream elements into maps by a classifier function and compose with downstream collectors.
What is groupingBy?
Collectors.groupingBy() partitions stream elements into a Map where each key maps to a list of matching elements. It is the stream equivalent of SQL's GROUP BY.
import java.util.*;
import java.util.stream.*;
record Person(String name, String city) {}
List<Person> people = List.of(
new Person("Alice","NYC"), new Person("Bob","LA"),
new Person("Carol","NYC"), new Person("Dave","LA"),
new Person("Eve","Chicago")
);
Map<String, List<Person>> byCity =
people.stream().collect(Collectors.groupingBy(Person::city));
byCity.forEach((city, ps) -> System.out.println(city + ": " + ps.size()));Downstream Collector: counting
Compose groupingBy with a downstream collector to aggregate instead of listing:
Map<String, Long> countByCity =
people.stream().collect(
Collectors.groupingBy(Person::city, Collectors.counting())
);
countByCity.forEach((city, n) -> System.out.println(city + " -> " + n));
// NYC -> 2, LA -> 2, Chicago -> 1All lessons in this course
- groupingBy: Classifying Elements
- partitioningBy and counting
- toMap, joining, and summarizing
- Building a Custom Collector