Java Streams: group a list by field

Group a list of employees by department using Collectors.groupingBy.

Code
Map<String, List<Employee>> byDept = employees.stream()
        .collect(Collectors.groupingBy(Employee::getDepartment));
byDept.forEach((dept, list) ->
        System.out.println(dept + " -> " + list.size()));
Output
Engineering -> 12
Sales -> 7
HR -> 3
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-25