Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
keyExtractorFunction<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 Oleg

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.