thenComparingInt, thenComparingLong, thenComparingDouble
What you'll learn: How to chain primitive-specialized comparators for efficient multi-level sorting without autoboxing overhead.
The Core Idea
You already know thenComparing() lets you define secondary sort criteria. When those secondary criteria are primitive numeric types (int, long, or double), Java provides specialized methods: thenComparingInt(), thenComparingLong(), and thenComparingDouble(). These avoid the performance cost of boxing primitives into Integer, Long, or Double objects.
Why Use Primitive Specializations?
Think of it like sorting mail: first by zip code (int), then by house number (int). Using thenComparing() would wrap each house number in an envelope before comparing—wasteful! The specialized methods compare the raw numbers directly.
List<Person> people = Arrays.asList(
new Person("Alice", 30, 65000),
new Person("Bob", 30, 70000),
new Person("Carol", 25, 65000)
);
Comparator<Person> comp = Comparator.comparingInt(Person::getAge)
.thenComparingInt(Person::getSalary);
people.sort(comp);
// Result: Carol(25), Alice(30, 65000), Bob(30, 70000)
Chaining Multiple Primitives
You can chain as many levels as needed:
Comparator<Product> byPriority = Comparator
.comparingInt(Product::getCategoryId)
.thenComparingDouble(Product::getPrice)
.thenComparingLong(Product::getTimestamp);
This sorts first by category (int), then price (double), then timestamp (long)—all without boxing.
When to Use Them
Use these methods whenever your secondary sort keys are primitive numeric types. The performance gain is modest for small collections but significant when sorting thousands of objects repeatedly.
Key Takeaway: thenComparingInt(), thenComparingLong(), and thenComparingDouble() enable efficient multi-level sorting of primitive numeric properties by avoiding autoboxing overhead while maintaining clean, readable comparator chains.