Java - guide Sorting a List of Custom Objects with Multiple Criteria Using Comparator
I'm stuck on something that should probably be simple. I'm writing unit tests and I'm relatively new to this, so bear with me. I've been struggling with this for a few days now and could really use some help. I've been banging my head against this for hours. I'm having trouble sorting a list of custom objects in Java, specifically when I try to apply multiple sorting criteria using a `Comparator`. My class, `Employee`, has properties for `name`, `age`, and `salary`, and I want to sort first by `salary` in descending order, and then by `age` in ascending order if salaries are equal. Here's what I have: ```java import java.util.*; class Employee { String name; int age; double salary; Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } } public class Main { public static void main(String[] args) { List<Employee> employees = Arrays.asList( new Employee("Alice", 30, 70000), new Employee("Bob", 25, 70000), new Employee("Charlie", 28, 50000) ); Collections.sort(employees, (e1, e2) -> { int salaryComparison = Double.compare(e2.salary, e1.salary); if (salaryComparison != 0) { return salaryComparison; } else { return Integer.compare(e1.age, e2.age); } }); for (Employee e : employees) { System.out.println(e.name + " | " + e.age + " | " + e.salary); } } } ``` However, the output I'm getting is not what I expect. Instead of being sorted by salary first and then by age, I see that employees with the same salary are not being sorted correctly by age. The output is: ``` Alice | 30 | 70000.0 Bob | 25 | 70000.0 Charlie | 28 | 50000.0 ``` It seems that `Bob` should come before `Alice` since they have the same salary but different ages. I've tried adjusting the comparison logic, but I consistently run into the same scenario. I'm using JDK 11. Can anyone point out what I'm doing wrong or suggest a better approach? My development environment is Windows. What am I doing wrong? This is part of a larger API I'm building. This is my first time working with Java 3.9. What am I doing wrong? My development environment is Windows 10. I'd love to hear your thoughts on this.