CodexBloom - Programming Q&A Platform

Sorting a List of Custom Objects in Java Using Streams - Unexpected Order with Comparator

πŸ‘€ Views: 81 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-16
java java-stream sorting Java

I recently switched to I'm trying to sort a list of custom objects in Java using the Streams API, but I'm working with an unexpected sorting order... I have a class called `Employee` with fields `name` (String) and `salary` (double). I'm attempting to sort a list of employees based on their salary in ascending order, but it seems to be sorting incorrectly due to my comparator implementation. Here’s the code snippet that I’m using: ```java import java.util.*; import java.util.stream.Collectors; class Employee { String name; double salary; Employee(String name, double salary) { this.name = name; this.salary = salary; } @Override public String toString() { return name + ": " + salary; } } public class Main { public static void main(String[] args) { List<Employee> employees = Arrays.asList( new Employee("Alice", 70000), new Employee("Bob", 50000), new Employee("Charlie", 90000) ); List<Employee> sortedEmployees = employees.stream() .sorted(Comparator.comparingDouble(emp -> emp.salary)) .collect(Collectors.toList()); sortedEmployees.forEach(System.out::println); } } ``` When I run this code, the output is: ``` Alice: 70000.0 Charlie: 90000.0 Bob: 50000.0 ``` I expected the output to be sorted from lowest to highest salary, like this: ``` Bob: 50000.0 Alice: 70000.0 Charlie: 90000.0 ``` It seems that `sorted()` might not be handling the `salary` values correctly, but I need to figure out why. I've also verified that all salary values are indeed double types. The version of Java I'm using is 11, and I’m running this in an IntelliJ IDEA environment. Any insights on what might be going wrong would be greatly appreciated! I'm on Windows 10 using the latest version of Java.