To group a list of employees by their department names using Java 8, you can utilize the Stream API and the Collectors class. Here’s an example of how you can achieve this:

import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; 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; } } public class EmployeeGroupingExample { public static void main(String[] args) { // Create a list of employees List<Employee> employees = new ArrayList<>(); employees.add(new Employee("John", "Sales")); employees.add(new Employee("Alice", "Marketing")); employees.add(new Employee("Mike", "Sales")); employees.add(new Employee("Emma", "HR")); employees.add(new Employee("David", "Marketing")); employees.add(new Employee("Sophia", "HR")); // Group employees by department Map<String, List<Employee>> employeesByDepartment = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment)); // Print the employees in each department for (Map.Entry<String, List<Employee>> entry : employeesByDepartment.entrySet()) { String department = entry.getKey(); List<Employee> departmentEmployees = entry.getValue(); System.out.println("Employees in department: " + department); for (Employee employee : departmentEmployees) { System.out.println("- " + employee.getName()); } System.out.println(); } } }
Output:
Employees in department: HR - Emma - Sophia Employees in department: Marketing - Alice - David Employees in department: Sales - John - Mike
In the above example, we have a list of employees, and each employee has a name and a department. By using the Collectors.groupingBy
method along with the Employee::getDepartment
method reference, we group the employees based on their department names. The result is stored in a Map<String, List<Employee>>
where the department names are the keys, and the corresponding employees are the values. Finally, we iterate over the map entries and print the employees in each department.