CodexBloom - Programming Q&A Platform

Inconsistent Sorting Behavior with Custom Sorting in Java Streams

👀 Views: 56 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-07
java streams sorting comparator

Could someone explain I'm writing unit tests and I am working with an scenario when sorting a list of objects using Java Streams. I have a list of `Person` objects that I want to sort first by age and then by name alphabetically if the ages are the same. Here is my `Person` class: ```java public class Person { private int age; private String name; public Person(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } } ``` I am attempting to sort the list using Java Streams like this: ```java List<Person> people = Arrays.asList( new Person(30, "Alice"), new Person(25, "Bob"), new Person(30, "Charlie"), new Person(25, "Diana") ); List<Person> sortedPeople = people.stream() .sorted(Comparator.comparingInt(Person::getAge) .thenComparing(Person::getName)) .collect(Collectors.toList()); ``` However, when I print the sorted list, I get this output: ``` Bob Diana Alice Charlie ``` This is not the order I expected. I thought it should be sorted first by age and then by name, resulting in: ``` Bob Diana Alice Charlie ``` I'm using Java 11 and the output seems to be correct based on the criteria, but I'm getting confused when I see that the order of "Alice" and "Charlie" appears to be switched. I even tried to debug the comparator and it seems to be working fine. Could anyone help clarify what might be going wrong in my sorting logic? Is there a specific edge case with the comparator that I am missing? Any insights would be appreciated. Thanks in advance! Is there a better approach?