A Java program that takes a list of Employee objects, filters those with salary > 100000, groups them by department, sorts each department’s employees by salary in descending order, and returns a Map<String, List<Employee>>.
Here’s a clean Java 8+ solution using Streams:
import java.util.*;
import java.util.stream.Collectors;
class Employee {
private String name;
private String department;
private double salary;
// Constructor
public Employee(String name, String department, double salary) {
this.name = name;
this.department = department;
this.salary = salary;
}
// Getters
public String getName() { return name; }
public String getDepartment() { return department; }
public double getSalary() { return salary; }
@Override
public String toString() {
return name + " (" + salary + ")";
}
}
public class EmployeeProcessor {
public static Map<String, List<Employee>> processEmployees(List<Employee> employees) {
return employees.stream()
// ✔ Filter salary > 100000
.filter(e -> e.getSalary() > 100000)
// ✔ Group by department
.collect(Collectors.groupingBy(
Employee::getDepartment,
// ✔ Sort each department’s employees by salary DESC
Collectors.collectingAndThen(
Collectors.toList(),
list -> list.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
.collect(Collectors.toList())
)
));
}
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Alice", "IT", 120000),
new Employee("Bob", "Finance", 95000),
new Employee("Charlie", "IT", 135000),
new Employee("David", "Finance", 150000),
new Employee("Eve", "HR", 110000),
new Employee("Frank", "HR", 105000)
);
Map<String, List<Employee>> result = processEmployees(employees);
result.forEach((dept, empList) -> {
System.out.println(dept + " → " + empList);
});
}
}
✅ Explanation
filter(e -> e.getSalary() > 100000)→ keeps only employees with salary > 100000.groupingBy(Employee::getDepartment, ...)→ groups employees by department.collectingAndThen(Collectors.toList(), ...)→ allows post-processing of each group.- Inside, we
sorted(Comparator.comparingDouble(Employee::getSalary).reversed())→ sorts employees by salary descending.
🖥 Sample Output
IT → [Charlie (135000.0), Alice (120000.0)]
Finance → [David (150000.0)]
HR → [Eve (110000.0), Frank (105000.0)]
Would you like me to also show you a version using Map<String, TreeSet<Employee>> (which keeps them sorted automatically), or do you prefer sticking with List<Employee> for flexibility?
No comments:
Post a Comment