Complex Sorting Chains: Three or More Criteria
What you'll learn: How to chain multiple thenComparing() calls together to sort objects by three, four, or even more properties in sequence.
You've already seen how thenComparing() adds a secondary sort criterion when the primary one results in a tie. But what if you need even finer control? Java's comparator chaining doesn't stop at two levels—you can keep adding thenComparing() calls to handle as many tie-breaking rules as your domain requires.
The Core Idea
Each thenComparing() returns a new Comparator, which means you can immediately call another thenComparing() on it. Think of it like a cascading decision tree: "First sort by A; if A is equal, sort by B; if B is also equal, sort by C; if C is still equal, sort by D..."—and so on.
The pattern looks like this:
Comparator<Employee> complexComparator =
Comparator.comparing(Employee::getDepartment)
.thenComparing(Employee::getSalary)
.thenComparing(Employee::getLastName)
.thenComparing(Employee::getFirstName);
This sorts employees first by department, then by salary (within each department), then by last name (for employees with the same salary), and finally by first name if all else is equal.
Mixing Types
You can mix method references, lambdas, and even primitive specializations:
Comparator<Product> productSort =
Comparator.comparing(Product::getCategory)
.thenComparingInt(Product::getPriority)
.thenComparingDouble(Product::getPrice)
.thenComparing(Product::getName);
Each level only matters when all previous comparisons resulted in equality. The chain reads naturally from left to right, making your sort logic self-documenting.
Key Takeaway: You can chain as many thenComparing() calls as needed to build complex, multi-level sorting logic in a clear, readable, and type-safe way.