How do you group elements using Java streams?

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

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).

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.

Last updated: 11 November 2026

Previous question: How do you use flatMap() to flatten nested lists in Java streams?

Next question: What does peek() do in Java streams?

More Stream API Coding Questions - Level I interview questions

All Stream API Coding Questions - Level I questions