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