Java 8: Group a list with Collectors.groupingBy

groupingBy turns a stream into a Map keyed by a classifier function.

Code
record Person(String name, String city) {}
List<Person> people = List.of(
        new Person("Ava", "NYC"), new Person("Ben", "LA"),
        new Person("Cara", "NYC"));

Map<String, List<String>> byCity = people.stream()
        .collect(Collectors.groupingBy(
                Person::city,
                Collectors.mapping(Person::name, Collectors.toList())));
System.out.println(byCity);
Output
{NYC=[Ava, Cara], LA=[Ben]}
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26