CKTIS / Java
Comparator.thenComparing — add a tie-breaker
Combine sorting criteria so that the next criterion is used only when the earlier ones cannot decide the order of a pair.
Version: Java SE 21
Syntax
import java.util.Comparator;
import java.util.function.Function;
// Signatures of the default methods on Comparator<T>:
default Comparator<T> thenComparing(Comparator<? super T> other)
default <U extends Comparable<? super U>> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor)
default <U> Comparator<T> thenComparing(Function<? super T, ? extends U> keyExtractor, Comparator<? super U> keyComparator)
// Example call on a Comparator<Person>:
byAge.thenComparing(Person::lastName)Comparator.thenComparing is a family of default methods on java.util.Comparator, available since Java 8 and included in Java SE 21. Comparator.thenComparing() is shorthand for the method name, not a no-argument overload. Call it on an existing comparator to get a composite comparator. The original comparator is unchanged, and the call itself does not sort anything.
For a pair a and b, the next criterion is used only if the existing compare(a, b) returns 0. That is a tie according to the comparator, not necessarily equality according to equals. In a chain, the third criterion is reached only if the first two tie. If all criteria tie, the composite comparator returns 0, and the stable List.sort keeps the pair in its original relative order.
thenComparing(other) delegates comparison of the same elements to another comparator. thenComparing(keyExtractor) extracts a Comparable key from each element and compares the keys in their natural order. thenComparing(keyExtractor, keyComparator) compares the extracted keys with the supplied comparator; the keys do not have to implement Comparable.
Passing null as any argument throws NullPointerException. A null returned by the key extractor is a separate issue: the natural-order overload does not handle null keys. If they are possible, you can supply a key comparator such as Comparator.nullsLast(Comparator.naturalOrder()). For primitive keys, thenComparingInt, thenComparingLong, and thenComparingDouble avoid boxing the keys.
Examples
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Person(int age, String lastName) {}
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person(21, "Smith"),
new Person(30, "Adams"),
new Person(21, "Brown")
));
Comparator<Person> byAge = Comparator.comparingInt(Person::age);
Comparator<Person> byAgeThenLastName = byAge.thenComparing(Person::lastName);
people.sort(byAgeThenLastName);
for (Person person : people) {
System.out.println(person.age() + " " + person.lastName());
}
}
}Result
21 Brown 21 Smith 30 Adams
`Comparator.comparingInt(Person::age)` orders people by ascending age. `Person::lastName` breaks the tie between the two 21-year-olds: Brown comes before Smith. Adams comes last because of age, even though Adams would come first in natural string order.
Related lessons
- Java · Lesson 8 · Advanced · Version: 2
- Java · Lesson 48 · Basic · Version: 2
- Java · Lesson 35 · Intermediate · Version: 2