Java Lambda Comparator排序员工列表代码纠错求助
Hi there! As a Java newbie, it's totally normal to hit snags with collections and lambdas—let's walk through fixing your code step by step. I'll start with corrected full code for all three classes, then break down the key fixes and concepts so you understand why each part works.
First, Let's Correct the Employee & Department Classes
These classes need proper getters (so we can access employee properties for sorting) and basic constructors/toString for usability:
Employee.java
public class Employee { private int id; private String name; private double salary; // Constructor to create employee instances public Employee(int id, String name, double salary) { this.id = id; this.name = name; this.salary = salary; } // Getters are REQUIRED for sorting (we need to access these properties!) public int getId() { return id; } public String getName() { return name; } public double getSalary() { return salary; } // Override toString to print meaningful employee info @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", salary=" + salary + '}'; } }
Department.java
import java.util.List; public class Department { private String departmentName; private List<Employee> employees; // Constructor to create department with its employees public Department(String departmentName, List<Employee> employees) { this.departmentName = departmentName; this.employees = employees; } // Getter to access the list of employees in the department public List<Employee> getEmployees() { return employees; } public String getDepartmentName() { return departmentName; } }
Corrected CompanyTest1.java (Core Functionality)
This class handles collecting all employees into allEmployees and sorting them using List.sort() with lambda-based Comparator:
import java.util.ArrayList; import java.util.List; public class CompanyTest1 { public static void main(String[] args) { // Step 1: Create sample employees Employee emp1 = new Employee(3, "Alice", 8000.0); Employee emp2 = new Employee(1, "Bob", 6000.0); Employee emp3 = new Employee(2, "Charlie", 7500.0); Employee emp4 = new Employee(4, "David", 9000.0); // Step 2: Create departments and assign employees List<Employee> devTeam = new ArrayList<>(); devTeam.add(emp1); devTeam.add(emp2); Department devDept = new Department("Development", devTeam); List<Employee> hrTeam = new ArrayList<>(); hrTeam.add(emp3); hrTeam.add(emp4); Department hrDept = new Department("HR", hrTeam); // Step 3: Create list of all company departments List<Department> companyDepartments = new ArrayList<>(); companyDepartments.add(devDept); companyDepartments.add(hrDept); // Step 4: Collect ALL employees into allEmployees list List<Employee> allEmployees = new ArrayList<>(); for (Department dept : companyDepartments) { // Use addAll() to bulk-add all employees from a department allEmployees.addAll(dept.getEmployees()); } // Step 5: Sort using List.sort() + Lambda Comparators // Example 1: Sort by employee ID (ascending) allEmployees.sort((e1, e2) -> Integer.compare(e1.getId(), e2.getId())); System.out.println("Sorted by ID (Ascending):"); allEmployees.forEach(System.out::println); System.out.println("\n------------------------\n"); // Example 2: Sort by salary (descending) allEmployees.sort((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary())); System.out.println("Sorted by Salary (Descending):"); allEmployees.forEach(System.out::println); System.out.println("\n------------------------\n"); // Example 3: Sort by name (alphabetical order) allEmployees.sort((e1, e2) -> e1.getName().compareTo(e2.getName())); System.out.println("Sorted by Name (Alphabetical):"); allEmployees.forEach(System.out::println); } }
Key Fixes & Explanations for Newbies
Let's go over the most common mistakes that might have broken your original code:
Missing Getter Methods
This is the #1 issue for newbies! To sort employees by their ID, name, or salary, yourEmployeeclass needs public getter methods to access those private properties. Without them, the lambda can't read the values to compare.Incorrectly Collecting Employees
Instead of adding employees one by one, useaddAll()to add every employee from a department's list toallEmployeesin one step. This is cleaner and avoids missing any employees.Lambda Comparator Syntax
TheList.sort()method takes aComparator—using a lambda simplifies this to(e1, e2) -> comparisonLogic:- For integers (like ID), use
Integer.compare(a, b)to avoid overflow issues from direct subtraction. - For doubles (like salary), use
Double.compare(a, b). - For strings (like name), use the built-in
compareTo()method for alphabetical sorting.
- For integers (like ID), use
Uninitialized Collections
Always initialize yourListinstances withnew ArrayList<>()—if you forget this, you'll get aNullPointerExceptionwhen trying to add elements.
内容的提问来源于stack exchange,提问作者GMan91




