CodexBloom - Programming Q&A Platform

Java 17: implementing Custom Comparator and Sorting a List of Objects with Different Attributes

πŸ‘€ Views: 16 πŸ’¬ Answers: 1 πŸ“… Created: 2025-08-26
java sorting comparator java17 Java

I'm refactoring my project and I'm working with a scenario while sorting a list of custom objects in Java 17 using a custom comparator... I have a class `Person` with attributes `name`, `age`, and `salary`. I want to sort a list of `Person` objects first by age in ascending order and then by salary in descending order if ages are equal. Here’s how I’ve implemented the comparator: ```java import java.util.*; class Person { String name; int age; double salary; Person(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<Person> people = Arrays.asList( new Person("Alice", 30, 50000), new Person("Bob", 30, 60000), new Person("Charlie", 25, 70000) ); Collections.sort(people, new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { int ageCompare = Integer.compare(p1.age, p2.age); if (ageCompare == 0) { return Double.compare(p2.salary, p1.salary); } return ageCompare; } }); for (Person p : people) { System.out.println(p.name + " - Age: " + p.age + ", Salary: " + p.salary); } } } ``` The current output after sorting is: ``` Charlie - Age: 25, Salary: 70000.0 Alice - Age: 30, Salary: 50000.0 Bob - Age: 30, Salary: 60000.0 ``` I expected Bob to be printed before Alice since he has a higher salary but the output is not as expected. I’ve double-checked the comparator logic, and it seems correct to me. The behavior seems to stem from the sorting behavior when both ages are equal. I've also tested using `List.sort()` with a lambda expression, but it gives the same result. What could I be missing in the sorting logic or how can I ensure that the list sorts correctly by the specified attributes? I'm working in a Ubuntu 22.04 environment. Any examples would be super helpful. I'm using Java latest in this project. What am I doing wrong?