groupingBy turns a stream into a Map keyed by a classifier function.
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);
{NYC=[Ava, Cara], LA=[Ben]}
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