How would you implement a custom Comparator with multiple sort criteria (e.g., sort by last name, then by first name as a tiebreaker) using the Comparator.comparing() and thenComparing() fluent API?
Short answer
Comparator.comparing(keyExtractor) creates a Comparator based on a single sort key, and thenComparing(keyExtractor) chains an additional comparator applied only when the preceding comparator considers two elements equal (a tiebreaker), letting you compose complex multi-field…
Advertisement
AModel answer
Comparator.comparing(keyExtractor) creates a Comparator based on a single sort key, and thenComparing(keyExtractor) chains an additional comparator applied only when the preceding comparator considers two elements equal (a tiebreaker), letting you compose complex multi-field sort logic declaratively and readably rather than hand-writing a compare() method with nested if/else logic -- reversed() can further invert any comparator's direction for a specific field.
List<Employee> employees = ...;
employees.sort(
Comparator.comparing(Employee::getLastName)
.thenComparing(Employee::getFirstName)
.thenComparing(Employee::getSalary, Comparator.reverseOrder())
);
// Sorts by last name, ties broken by first name, further ties broken by salary descendingReal-world example
A reporting feature sorting a large employee list by department, then by seniority within each department, then alphabetically as a final tiebreaker, expresses this entire three-level sort declaratively in one fluent Comparator chain rather than a much harder-to-read hand-written multi-condition compareTo() implementation.
Likely follow-ups
- How does thenComparing() know when the previous comparator considered two elements 'equal' (compare() returned 0)?
- What's the performance implication of a multi-field Comparator chain compared to a single hand-optimized compare() method?
Related topics