You have a list of employees with fields like name, age, and department. Write a code snippet to group employees by department using Java Streams.
Solution
import java.util.*;
import java.util.stream.Collectors;
class Employee {
private String name;
private int age;
private String department;
// Constructor
public Employee(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
// Getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getDepartment() {
return department;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public class StreamExample {
public static void main(String[] args) {
// Create a list of employees
List<Employee> employees = Arrays.asList(
new Employee("John", 25, "HR"),
new Employee("Jane", 28, "Finance"),
new Employee("Jake", 22, "HR"),
new Employee("Jill", 35, "Finance"),
new Employee("Joe", 29, "IT")
);
// Group employees by department
Map<String, List<Employee>> employeesByDepartment = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
// Print the grouped employees
employeesByDepartment.forEach((department, empList) -> {
System.out.println(department + ": " + empList);
});
}
}
Explanation
stream(): Creates a stream from the list of employees.
Collectors.groupingBy(Employee::getDepartment):
Groups employees by the value of their department field.
Returns a Map>, where the key is the department, and the value is a list of employees in that department.
forEach():
Iterates over the Map and prints the department name and the list of employees.
Output
For the given list:
[
new Employee("John", 25, "HR"),
new Employee("Jane", 28, "Finance"),
new Employee("Jake", 22, "HR"),
new Employee("Jill", 35, "Finance"),
new Employee("Joe", 29, "IT")
]
The output will be:
HR: [John (25), Jake (22)]
Finance: [Jane (28), Jill (35)]
IT: [Joe (29)]
Edge Cases
Empty List: If the list is empty, the resulting map will also be empty.
All Employees in the Same Department: The map will have a single key with all employees grouped under it.
[
new Employee("John", 25, "HR"),
new Employee("Jane", 28, "HR"),
new Employee("Jake", 22, "HR")
]
Output:
HR: [John (25), Jane (28), Jake (22)]
Key Takeaways
Collectors.groupingBy() is a powerful tool for grouping data in streams.
Use toString() to customize how objects appear in the output.
Top comments (0)