Comparator
A Comparator is an order as an object: it takes two elements and answers how they compare, and it can be built for a class that has no natural order or for an order other than the natural one. The interface has a static method per shape of order and default methods that chain, so a sort by three keys is three method calls and no class of its own.
A comparator from a lambda
A comparator is a functional interface, so a lambda is enough: Comparator.comparing takes the key extractor and gives an order on that key. thenComparing adds a tie-break, and reverseOrder turns any order around:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Basics {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("pear", "fig", "apple"));
words.sort(Comparator.naturalOrder());
System.out.println(words);
words.sort(Comparator.reverseOrder());
System.out.println(words);
words.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println(words);
}
}
javac -Xlint:all Basics.java
java Basics
[apple, fig, pear]
[pear, fig, apple]
[fig, pear, apple]
The second line is the first reversed, word for word. The third sorts by length and then alphabetically among equal lengths: fig has three letters, pear four and apple five, so the tie-break never runs here. A comparator built this way is a Comparator<String> like any other, which is what the last section uses.
Two and three keys
The chain grows without limit, and each link reads one field of the record:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class People {
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("Grace", 45, "New York"),
new Person("Ada", 36, "London"),
new Person("Alan", 41, "London"),
new Person("Edsger", 36, "Amsterdam")));
people.sort(Comparator.comparing(Person::city)
.thenComparing(Person::age)
.thenComparing(Person::name));
for (Person person : people) {
System.out.println(person.city() + " " + person.age() + " " + person.name());
}
System.out.println("oldest " + people.stream().max(Comparator.comparingInt(Person::age)).orElseThrow().name());
}
}
record Person(String name, int age, String city) {
}
javac -Xlint:all People.java
java People
Amsterdam 36 Edsger
London 36 Ada
London 41 Alan
New York 45 Grace
oldest Grace
Amsterdam comes first because of the city, and inside London the age decides before the name, so Ada precedes Alan. The last line is a different use of the same interface: max takes a comparator and answers the greatest element, and the stream is two lessons away. comparingInt avoids boxing the age for the comparison.
null in the list
A natural-order comparator calls compareTo on an element, so a null element makes it throw. Comparator.nullsFirst and Comparator.nullsLast wrap another comparator and decide where null goes; the program shows both the failure and the two wrappers:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Nulls {
public static void main(String[] args) {
List<String> words = new ArrayList<>(Arrays.asList("pear", null, "apple"));
try {
words.sort(Comparator.naturalOrder());
} catch (NullPointerException e) {
System.out.println("naturalOrder: " + e.getClass().getSimpleName());
}
words.sort(Comparator.nullsLast(Comparator.naturalOrder()));
System.out.println(words);
Comparator<String> byLength = Comparator.comparing(String::length, Comparator.nullsFirst(Comparator.naturalOrder()));
List<String> copy = new ArrayList<>(Arrays.asList("bbb", "a", "cc"));
copy.sort(byLength);
System.out.println(copy);
}
}
javac -Xlint:all Nulls.java
java Nulls
naturalOrder: NullPointerException
[apple, pear, null]
[a, cc, bbb]
The sorted list puts the real words in order and null at the end, which is what nullsLast promises. The second comparator reads the length and sorts the strings of equal length naturally, so the list comes out by length: one, two and three letters.
The subtraction that overflows
A comparator written as (a, b) -> a - b is right for small numbers and wrong for large ones, because the difference of two ints can leave the range of the type. The program compares the largest and the smallest integer both ways:
import java.util.ArrayList;
import java.util.List;
public class Overflow {
public static void main(String[] args) {
int high = Integer.MAX_VALUE;
int low = Integer.MIN_VALUE;
System.out.println("difference: " + (high - low));
System.out.println("compare: " + Integer.compare(high, low));
List<Integer> values = new ArrayList<>(List.of(high, low));
values.sort((a, b) -> a - b);
System.out.println("subtract: " + values);
values.sort(Integer::compare);
System.out.println("compare: " + values);
}
}
javac -Xlint:all Overflow.java
java Overflow
difference: -1
compare: 1
subtract: [2147483647, -2147483648]
compare: [-2147483648, 2147483647]
The difference of the largest and the smallest integer is 4294967295, which does not fit in an int, and it wraps to -1: the comparator says the larger number comes first, so the sort leaves the pair in the wrong order. Integer.compare and Comparator.comparingInt compute the sign without subtracting and cannot wrap.
A comparator as an argument
Because an order is an object, a method can take one and sort by whatever the caller wants. The method below copies the list and sorts the copy, so the same input gives three reports:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Strategy {
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("Grace", 45, null),
new Person("Ada", 36, "London"),
new Person("Alan", 41, "London")));
System.out.println(sorted(people, Comparator.comparing(Person::name)));
System.out.println(sorted(people, Comparator.comparing(Person::age).reversed()));
System.out.println(sorted(people, Comparator.comparing(Person::city, Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparing(Person::name)));
}
static List<Person> sorted(List<Person> input, Comparator<Person> order) {
List<Person> copy = new ArrayList<>(input);
copy.sort(order);
return copy;
}
}
record Person(String name, int age, String city) {
}
javac -Xlint:all Strategy.java
java Strategy
[Person[name=Ada, age=36, city=London], Person[name=Alan, age=41, city=London], Person[name=Grace, age=45, city=null]]
[Person[name=Grace, age=45, city=null], Person[name=Alan, age=41, city=London], Person[name=Ada, age=36, city=London]]
[Person[name=Ada, age=36, city=London], Person[name=Alan, age=41, city=London], Person[name=Grace, age=45, city=null]]
The three lines are the same three records in three orders, and the method did not change. The second line reverses the age order with reversed, and the third sorts by city with null last and then by name, which puts Grace last because she has no city.
Exercises
- Sort the words of Basics by length and then in reverse alphabetical order.
- Sort the people by age descending and then by name ascending.
- Add a person with a null age and a comparator built with Comparator.nullsFirst.
- Write the comparator of Strategy as a named class and pass it to the method.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Comparator.comparingtake?Answer
A key extractor, and it builds an order on that key
The extractor is a function from the element to the key, and the key must be Comparable.
-
What does
thenComparingdo?Answer
Applies a second order to the elements the first one leaves equal
The second comparator runs only when the first answers zero.
-
Why is
(a, b) -> a - ba bad comparator for ints?Answer
The subtraction can overflow and give the wrong sign
The difference of two ints may not fit in an int, and the sign is then wrong.
-
What does this program print?
import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Q1 { public static void main(String[] args) { List<String> list = new ArrayList<>(List.of("bbb", "a", "cc")); list.sort(Comparator.comparing(String::length)); System.out.println(list); } }Answer
[a, cc, bbb]
The key is the length, so the strings come out one, two and three letters long.
-
What does this program print?
import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Q2 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(List.of(3, 1, 2)); list.sort(Comparator.reverseOrder()); System.out.println(list); } }Answer
[3, 2, 1]
reverseOrder is the natural order turned around, so the largest comes first.
-
What does this program print?
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Q3 { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList("b", null, "a")); list.sort(Comparator.nullsFirst(Comparator.naturalOrder())); System.out.println(list); } }Answer
[null, a, b]
nullsFirst puts the null at the front and the natural order sorts the rest.
-
What does this program print?
import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Q4 { public static void main(String[] args) { List<String> list = new ArrayList<>(List.of("bb", "a", "cc")); list.sort(Comparator.comparing(String::length).reversed()); System.out.println(list); } }Answer
[bb, cc, a]
Reversing the length order puts the longer strings first, and the equal pair keeps its order.
-
What does this program print?
import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Q5 { public static void main(String[] args) { List<Person> list = new ArrayList<>(List.of(new Person("b", 1), new Person("a", 2))); list.sort(Comparator.comparing(Person::age).thenComparing(Person::name)); System.out.println(list.get(0).name()); } } record Person(String name, int age) { }Answer
b
The younger person comes first, and the name tie-break is not needed.
-
Why does a null element throw in a natural-order sort?
Answer
The comparator calls compareTo on the element, and null has no methods
The natural order asks an element to compare itself, which a null cannot do.
-
What does
reversed()apply to?Answer
The comparator it is called on, as a new comparator
It returns a comparator that answers the opposite sign, leaving the original alone.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev