Grouping Elements

Grouping elements with the Stream API means partitioning a collection into a Map keyed by some derived property, using the Collectors.groupingBy collector.

Key Points: • Collectors.groupingBy(classifier) groups stream elements by the result of the classifier function into a Map<K, List<T>>. • The default downstream collector is toList(), but you can pass a second collector argument for counting, averaging, or further grouping. • groupingBy relies on the classifier's equals()/hashCode() to determine map keys, so it works cleanly with primitives and well-defined value types. • It's the Stream API equivalent of a SQL GROUP BY clause. • For a stable iteration order, use groupingBy with a TreeMap::new supplier instead of the default HashMap.

Example: Given a list of User objects, grouping by age produces a map where each age points to the list of users who share that age, so you could check how many 30-year-olds exist by inspecting map.get(30).

Code Example:

Map<Integer, List<User>> usersByAge = users.stream()
        .collect(Collectors.groupingBy(User::getAge));

Interview Tip: A concise interview answer is:

"I use Collectors.groupingBy(User::getAge) to group a stream of users into a Map<Integer, List<User>> keyed by age. It's the Stream API's equivalent of a SQL GROUP BY, and I can pass a downstream collector if I need counts or averages per group instead of the raw lists."