Comparator.thenComparing()
Adds a second sort criterion — for objects equal by the first one.
Available since: Java 8
Syntax
default <U extends Comparable<? super U>> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor)Parameters
| Parameter | Type | Description |
|---|---|---|
| keyExtractor | Function<T, U> / Comparator<T> | The second-level key or a ready comparator. |
Return value
Comparator<T>A new combined comparator.
Examples
By department, then by name:
record Employee(String dept, String name) {}
void main() {
var staff = new ArrayList<>(List.of(
new Employee("IT", "Oleg"), new Employee("HR", "Maria"),
new Employee("IT", "Anna"), new Employee("HR", "Ivan")));
staff.sort(Comparator.comparing(Employee::dept).thenComparing(Employee::name));
staff.forEach(e -> IO.println(e.dept() + " " + e.name()));
}Output:
HR Ivan
HR Maria
IT Anna
IT OlegNotes
The chain can go on: .thenComparing(...).thenComparing(...). For numbers there is thenComparingInt(). To reverse only the second criterion, pass a comparator: thenComparing(Employee::name, Comparator.reverseOrder()).
See also
- Comparator.comparing() — Creates a comparator that compares objects by one key.
- Comparator.reversed() — Returns a comparator with the opposite order. For the natural order there is Comparator.reverseOrder().
Related recipes
In the tutorial
- Sorting and comparators — Sorting collections in Java: natural order, reverse order, the Comparable interface, Comparator.comparing and sorting by several fields.