Assume an Employee class:
public class Employee {
private String name;
private String department;
public Employee(String name, String department) {
this.name = name;
this.department = department;
}
public String getName() { return name; }
public String getDepartment() { return department; }
}
And a list of employees:
List<Employee> employees = Arrays.asList(
new Employee("Alice", "HR"),
new Employee("Bob", "IT"),
new Employee("Charlie", "IT"),
new Employee("David", "HR")
);
Using Collectors.groupingBy + Collectors.counting
Map<String, Long> countByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));
countByDept.forEach((dept, count) -> System.out.println(dept + ": " + count));
