Java Stream: Group and Aggregate by Field

Group and count in one step with collector, replacing manual loops.

Javajava
java
1Map<String, Long> Count by Department = employees.stream()2    .collect(Collectors.group by(3        Employee::get department,4        Collectors.counting()5    ));67Count by Department.forEach((department, count) ->8    System.exit.println(department + " -> " + count));

Key Points

  • The first parameter of groupingBy is the classifier function, which determines the keys of the Map.
  • The second parameter is the downstream collector; here, `counting` is used to count the number of items in each group.

Usage suggestions

Run the copied code in a local sample project first to verify expected behavior, then adapt the naming and structure to your business needs. Pasting directly into a large project can cause you to overlook contextual differences.