Sub topic 7
Building comparators with comparing, thenComparing and reversed
Earlier chapters showed that a Comparator is a function that takes two objects and returns a negative number, zero or a positive number. Writing that function by hand for every sort is tedious and easy to get wrong. This chapter covers the factory and combinator methods on Comparator that build comparators from smaller pieces.
This chapter assumes you know Java generics, lambdas and method references, and the compare contract (sign of the result, consistency in both directions, transitivity). It also assumes you have seen List.sort.
The idea: describe the key, not the comparison
A hand-written comparator describes how to compare two objects:
Comparator<Person> byName = (a, b) -> a.getName().compareTo(b.getName());A comparator built with a factory describes only which key to compare. The library supplies the comparison:
Comparator<Person> byName = Comparator.comparing(Person::getName);The factory takes a key extractor, a function from Person to a value such as a String. It compares two people by extracting the key from each and comparing the keys. This removes the repeated a. and b. code, where a typo such as a.getName() against a.getName() would silently compare an object with itself.
The factory methods
| Method | What it does |
|---|---|
| `comparing(keyExtractor)` | Compares the extracted keys using their natural order. The key type must be `Comparable`. |
| `comparing(keyExtractor, keyComparator)` | Compares the extracted keys using a comparator you supply. |
| `comparingInt`, `comparingLong`, `comparingDouble` | Same as `comparing`, for primitive keys. They avoid boxing. |
| `naturalOrder()` | A comparator that calls `compareTo` on the elements. |
| `reverseOrder()` | The opposite of `naturalOrder()`. |
| `thenComparing(...)` | An instance method that adds a tie-breaker. |
| `reversed()` | An instance method that returns the opposite ordering. |
Prefer comparingInt when the key is an int. comparing(Person::getAge) works too, but it boxes each age into an Integer for every comparison. comparingInt calls int-returning code directly and also states the intent clearly.
Adding tie-breakers with thenComparing
Sorting by age leaves people of the same age in an unspecified relative order, or in their original order if the sort is stable. thenComparing adds a second key that is consulted only when the first key says "equal".
Internally, the combined comparator does this:
- Run the first comparator on
aandb. - If the result is not zero, return it.
- Otherwise, return the result of the second comparator.
You can chain as many thenComparing calls as you need. Later keys are consulted only when every earlier key ties.
thenComparing has these overloads:
thenComparing(Comparator<? super T> other)takes a full comparator.thenComparing(Function<? super T, ? extends U> keyExtractor)takes a key extractor, with natural order on the key.thenComparing(keyExtractor, keyComparator)takes a key extractor and a comparator for the key.thenComparingInt,thenComparingLongandthenComparingDoubletake primitive keys.
A runnable example
The program below defines a Person with a name, an age and a city, and sorts the same list four ways.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparatorChains {
static class Person {
private final String name;
private final int age;
private final String city;
Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
String getName() { return name; }
int getAge() { return age; }
String getCity() { return city; }
@Override
public String toString() { return name + " (" + age + ")"; }
}
static List<Person> sample() {
return new ArrayList<>(List.of(
new Person("Ana", 31, "Lyon"),
new Person("Bo", 25, "Oslo"),
new Person("Cy", 31, "Bern"),
new Person("Di", 25, "Lyon")));
}
public static void main(String[] args) {
List<Person> people = sample();
people.sort(Comparator.comparingInt(Person::getAge)
.thenComparing(Person::getName));
System.out.println("age, name: " + people);
people = sample();
people.sort(Comparator.comparingInt(Person::getAge)
.reversed()
.thenComparing(Person::getName));
System.out.println("age desc, name: " + people);
people = sample();
people.sort(Comparator.comparingInt(Person::getAge)
.thenComparing(Person::getName)
.reversed());
System.out.println("whole chain reversed: " + people);
people = sample();
people.sort(Comparator.comparingInt(Person::getAge)
.thenComparing(Person::getName, Comparator.reverseOrder()));
System.out.println("age, name desc: " + people);
}
}The output is:
age, name: [Bo (25), Di (25), Ana (31), Cy (31)]
age desc, name: [Ana (31), Cy (31), Bo (25), Di (25)]
whole chain reversed: [Cy (31), Ana (31), Di (25), Bo (25)]
age, name desc: [Di (25), Bo (25), Cy (31), Ana (31)]Compare the second and third lines. They differ only in where .reversed() sits, and they give different results.
Where reversed applies
reversed() is an instance method. It reverses the comparator it is called on, and that comparator is the whole chain built so far.
- In
comparingInt(...).reversed().thenComparing(...), only the age comparison is reversed. The name tie-breaker is added afterward and stays ascending. - In
comparingInt(...).thenComparing(...).reversed(), the combined comparator is reversed, so both keys run in descending order.
To reverse a single key in the middle or at the end of a chain, pass a key comparator instead of calling reversed(). That is what the fourth example does with thenComparing(Person::getName, Comparator.reverseOrder()).
reversed() swaps the two arguments. It does not negate the result. This matters because negating Integer.MIN_VALUE gives Integer.MIN_VALUE again, so negation is unsafe. Swapping arguments is always correct.
The type inference trap
This line looks reasonable but does not compile:
// Does not compile: p is inferred as Object, so p.getName() is not found
// Comparator<Person> c = Comparator.comparing(p -> p.getName()).reversed();The compiler infers the type arguments of comparing from the call. When you chain .reversed() onto the result, the call is no longer in an assignment context, so the target type Comparator<Person> cannot guide inference. With an implicit lambda p -> ..., the compiler has nothing to infer T from and uses Object.
There are three fixes. All of them compile:
import java.util.Comparator;
public class InferenceFixes {
record Person(String name, int age) {
String getName() { return name; }
}
public static void main(String[] args) {
// 1. A method reference carries its own type information.
Comparator<Person> a = Comparator.comparing(Person::getName).reversed();
// 2. An explicitly typed lambda parameter.
Comparator<Person> b = Comparator.comparing((Person p) -> p.getName()).reversed();
// 3. A key comparator, which needs no reversed() call at all.
Comparator<Person> c = Comparator.comparing(Person::getName, Comparator.reverseOrder());
Person x = new Person("Ana", 31);
Person y = new Person("Bo", 25);
System.out.println(a.compare(x, y) > 0); // true: "Ana" is after "Bo" when reversed
System.out.println(b.compare(x, y) > 0); // true
System.out.println(c.compare(x, y) > 0); // true
}
}The same problem appears with thenComparing only when you chain .reversed() after a lambda-based first step. Using method references throughout avoids it.
Natural and reverse order as building blocks
Comparator.naturalOrder() and Comparator.reverseOrder() are most useful as the second argument of a keyed factory. They also work on their own for types that are already Comparable:
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class NaturalAndReverse {
public static void main(String[] args) {
List<String> words = Arrays.asList("pear", "fig", "apple");
words.sort(Comparator.reverseOrder());
System.out.println(words); // [pear, fig, apple]
words.sort(Comparator.comparing(String::length)
.thenComparing(Comparator.naturalOrder()));
System.out.println(words); // [fig, pear, apple]
}
}The second sort orders by length first. Words of equal length would then fall back to alphabetical order, although here every length is different.
Keys that can be null
comparing calls the extractor on both objects and passes the keys to compareTo. If a key is null, that call throws a NullPointerException. Wrap the key comparator to say where nulls go:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class NullKeys {
record Contact(String name, String city) {
String getName() { return name; }
String getCity() { return city; }
}
public static void main(String[] args) {
List<Contact> contacts = new ArrayList<>(List.of(
new Contact("Ana", "Lyon"),
new Contact("Bo", null),
new Contact("Cy", "Bern")));
contacts.sort(Comparator.comparing(Contact::getCity,
Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparing(Contact::getName));
contacts.forEach(c -> System.out.println(c.getName() + " " + c.getCity()));
// Cy Bern
// Ana Lyon
// Bo null
}
}Here nullsLast handles only the key city. A Contact that is itself null would still fail. To tolerate null elements, wrap the whole comparator in nullsFirst or nullsLast.
Common mistakes
- Reversing too much.
reversed()at the end of a chain flips every key. Use a key comparator when only one key should flip. - Forgetting a tie-breaker. A comparator that ties on equal keys is legal. For output you want to be deterministic, add a final unique key such as an ID.
- Boxing in hot paths.
comparing(Person::getAge)boxes. UsecomparingIntwhen sorting large lists. - Keys that are not
Comparable.comparing(Person::getAddress)fails to compile ifAddressdoes not implementComparable. Pass a key comparator in that case. - Mutable or expensive key extractors. The extractor runs on both objects for every comparison, which is about n log n times per sort. Keep it a cheap getter.
Exercises
Exercise
Given List<Person> people with getName(), getAge() and getCity(), write one comparator that sorts by city ascending, then by age descending, then by name ascending. Why does Comparator.comparing(Person::getCity).thenComparingInt(Person::getAge).reversed().thenComparing(Person::getName) not do this?
Show answer
Use Comparator.comparing(Person::getCity).thenComparing(Person::getAge, Comparator.reverseOrder()).thenComparing(Person::getName). Another valid form is Comparator.comparing(Person::getCity).thenComparing(Comparator.comparingInt(Person::getAge).reversed()).thenComparing(Person::getName). The version in the question reverses the whole chain built so far, which is city and age together, so the city would end up descending as well. Only the name tie-breaker added after reversed() stays ascending.
Exercise
Why does Comparator<Person> c = Comparator.comparing(p -> p.getName()).reversed(); fail to compile, and what are two ways to fix it?
Show answer
Because .reversed() is chained on the result of comparing, the compiler cannot use the target type Comparator<Person> to infer the type argument for comparing. It infers Object for p, so p.getName() is not found. Fix it with a method reference (Comparator.comparing(Person::getName).reversed()), with an explicitly typed lambda ((Person p) -> p.getName()), or with Comparator.comparing(Person::getName, Comparator.reverseOrder()).