Sub topic 7
Building Comparators with `comparing`, `thenComparing` and `reversed`
This chapter assumes that you know Java classes, generics, lambda expressions, method references, and basic collection sorting. The examples use Java 8 or later because the comparator factory methods and List.sort were added in Java 8.
A comparator is an object that defines an ordering between two values. The Comparator interface has one important method:
int compare(T first, T second)The result is negative when first comes before second, zero when they are equivalent for this ordering, and positive when first comes after second.
Build a comparator from a property
The static factory method Comparator.comparing creates a comparator from a function that extracts a property. For numeric properties, comparingInt, comparingLong, or comparingDouble avoids unnecessary boxing of primitive values.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparatorExample {
static final class Person {
private final String name;
private final int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
String getName() {
return name;
}
int getAge() {
return age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Ana", 31));
people.add(new Person("Bo", 25));
people.add(new Person("Cy", 31));
Comparator<Person> byAge =
Comparator.comparingInt(Person::getAge);
people.sort(byAge);
System.out.println(people);
Comparator<Person> byNameDescending =
Comparator.comparing(Person::getName).reversed();
people.sort(byNameDescending);
System.out.println(people);
}
}Person::getAge is a method reference. It tells comparingInt how to obtain an integer from each Person. The resulting comparator orders people from youngest to oldest.
Comparator.comparing(Person::getName) compares the returned String values using their natural ordering. Calling reversed() changes that ordering from ascending to descending.
Add tie-breakers with `thenComparing`
A comparator may leave several objects tied. For example, ordering by age alone does not distinguish Ana and Cy. Call thenComparing to add another comparison used only when the earlier comparison returns zero.
Comparator<Person> byAgeThenName =
Comparator.comparingInt(Person::getAge)
.thenComparing(Person::getName);This comparator first compares age. Among people with the same age, it compares names alphabetically. The order of the chain matters because each later comparator is a tie-breaker for the previous ones.
You can add more than one tie-breaker:
Comparator<Person> byAgeThenNameThenId =
Comparator.comparingInt(Person::getAge)
.thenComparing(Person::getName)
.thenComparingInt(Person::hashCode);Use a meaningful property for the final comparison. A hash code is not generally a reliable identity or stable business key.
| Method | Purpose |
|---|---|
| `comparing(keyExtractor)` | Compare values by a reference-valued property |
| `comparingInt(keyExtractor)` | Compare values by an `int` property |
| `thenComparing(...)` | Compare another property when there is a tie |
| `reversed()` | Reverse the comparator that it is called on |
Control where reversal happens
The location of reversed() determines which part of the ordering changes.
Comparator<Person> oldestFirstThenName =
Comparator.comparingInt(Person::getAge)
.reversed()
.thenComparing(Person::getName);This orders by age from oldest to youngest, then by name from A to Z. Only the age comparator is reversed.
By contrast:
Comparator<Person> ageThenNameReversed =
Comparator.comparingInt(Person::getAge)
.thenComparing(Person::getName)
.reversed();This reverses the complete ordering. Both age and name run in descending order.
A practical choice
Use comparingInt for primitive numeric keys and comparing for objects such as strings. Use thenComparing when the first key is not unique. If a key can be null, wrap its comparator with Comparator.nullsFirst or Comparator.nullsLast before adding it to the chain.
Exercise
Write a comparator that orders Person objects by age from youngest to oldest, and places names in reverse alphabetical order when ages match.
Show answer
Comparator<Person> order = Comparator.comparingInt(Person::getAge).thenComparing(Person::getName, Comparator.reverseOrder());