Sub topic 5
Comparator: ordering from outside the class
This chapter assumes you know Java classes, interfaces and generics, and that you can read a lambda. You should also know the Comparable interface and the rules a comparison must follow, both covered in earlier chapters. Lambdas and the factory methods such as comparing get their own chapters. Here the focus is the Comparator interface itself, written the long way, so you can see what the shortcuts expand to.
The problem Comparator solves
Comparable gives a class one natural ordering, fixed inside the class. That is not always enough:
- You may need to sort the same objects in several ways, for example
Personby age in one screen and by name in another. - You may not own the class. You cannot add
compareTotoStringor to a class from a library. - The natural ordering may exist but be the wrong one for the task at hand.
java.util.Comparator<T> solves this by moving the comparison into a separate object. The class being sorted does not change, and you can write as many comparators as you need.
The compare method
The core of the interface is one abstract method:
int compare(T o1, T o2);It follows the same sign convention as compareTo:
- A negative number means
o1comes beforeo2. - Zero means the two are equal for ordering purposes.
- A positive number means
o1comes aftero2.
The difference is where the comparison lives. With Comparable, a.compareTo(b) is a method on one of the two objects. With Comparator, a third object calls comparator.compare(a, b), and neither argument needs to know about it.
Writing a comparator as a class
The most explicit form is a named class that implements Comparator<T>. This example assumes the Person class from the previous chapter, with getName(), getAge() and a toString that prints Ana (31).
import java.util.Comparator;
public class ByNameComparator implements Comparator<Person> {
@Override
public int compare(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
}This comparator delegates to String.compareTo, which is the usual way to compare a field that already has a natural ordering. For an int field, use Integer.compare(x, y). Do not subtract the values, because subtraction can overflow. A later chapter covers that pitfall in detail.
A named class is a good fit when the comparator is reused in many places or needs a name that documents its intent.
Passing a comparator to the sorting methods
Every sorting entry point that accepts a Comparator follows the same rule: the comparator you pass replaces the natural ordering.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
public class ComparatorDemo {
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("Cy", 31), new Person("Ana", 31), new Person("Bo", 25)));
people.sort(new ByNameComparator());
System.out.println(people); // [Ana (31), Bo (25), Cy (31)]
Comparator<Person> byAgeDescending = new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return Integer.compare(b.getAge(), a.getAge());
}
};
Collections.sort(people, byAgeDescending);
System.out.println(people); // [Ana (31), Cy (31), Bo (25)]
TreeSet<Person> byName = new TreeSet<>(new ByNameComparator());
byName.addAll(people);
System.out.println(byName); // [Ana (31), Bo (25), Cy (31)]
TreeSet<Person> byAge = new TreeSet<>(byAgeDescending);
byAge.addAll(people);
System.out.println(byAge); // [Ana (31), Bo (25)]
}
}Four things in this program are worth studying.
people.sort(comparator)andCollections.sort(people, comparator)behave the same way. The first is the newer form.byAgeDescendingis an anonymous class. It is the same asByNameComparatorwithout a name. Before Java 8 this was the standard way to write a one-off comparator. You will rarely write one today, but you will meet it in older code.- In the second line of output, Ana still comes before Cy. Both are 31, and the sort is stable. Stable means elements that compare as equal keep their relative order from before the sort. The list was already
Ana, Bo, Cyfrom the first sort, so Ana and Cy stay in that order. - The last line shows something surprising.
byAgehas only two people. ATreeSettreats a comparison result of 0 as "same element", so Cy was dropped because it compared equal to Ana. TheTreeSetnever callsequalshere. Why this matters is the subject of a later chapter on consistency withequals.
Reversing the order
To reverse a comparator you can swap the arguments, as byAgeDescending does with Integer.compare(b.getAge(), a.getAge()). This is correct and cheap, but it is easy to swap the wrong pair or forget which one you swapped. The interface offers a default method for this:
Comparator<Person> byNameDescending = new ByNameComparator().reversed();reversed() returns a new comparator that calls the original with its arguments swapped. The original is not changed. The standard library also provides Comparator.naturalOrder() and Comparator.reverseOrder() for types that implement Comparable. Combining several comparators into one is covered in the chapter on factory and combinator methods.
Comparators for classes you do not own
The main benefit of Comparator is that it works on any type. The standard library already ships one for strings that ignores case:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.String;That import list is wrong on purpose to show a common slip: String lives in java.lang and needs no import. Here is the correct, complete version:
import java.util.ArrayList;
import java.util.List;
public class CaseDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("cherry", "Banana", "apple"));
words.sort(null); // natural ordering
System.out.println(words); // [Banana, apple, cherry]
words.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(words); // [apple, Banana, cherry]
}
}String.CASE_INSENSITIVE_ORDER is a Comparator<String> constant. The natural ordering puts uppercase letters before lowercase ones because it compares character codes. The comparator gives the order a person would expect.
The first call also shows a useful rule. Passing null as the comparator means "use the natural ordering". List.sort(null), Arrays.sort(array, null) and new TreeSet<>((Comparator<T>) null) all behave that way. The TreeSet form needs a cast because new TreeSet<>(null) is ambiguous between a comparator and a collection argument.
Comparator is a functional interface
Comparator has exactly one abstract method, compare, so it is a functional interface. The interface also declares boolean equals(Object). That does not count as a second abstract method, because every object already has an equals from Object.
This is why a lambda can stand in for the whole class or anonymous class:
Comparator<Person> byAgeDescending = (a, b) -> Integer.compare(b.getAge(), a.getAge());The compiler treats the lambda as an implementation of compare. Everything in this chapter still applies. The lambda is shorter, and the contract is the same.
The contract still applies
A comparator must obey the same rules as compareTo. Sorting algorithms and sorted collections rely on them.
- Antisymmetry.
sign(compare(a, b))must equal-sign(compare(b, a)). - Transitivity. If
compare(a, b) > 0andcompare(b, c) > 0, thencompare(a, c) > 0. - Consistency of ties. If
compare(a, b) == 0, thenaandcmust compare to any third element in the same way asbdoes. - Stability over time. The result for a given pair must not change between calls, unless the objects themselves change.
If you break these rules, behavior depends on the algorithm. List.sort may throw IllegalArgumentException with the message "Comparison method violates its general contract!", or it may quietly return an order that is not sorted. A TreeSet may lose or misplace elements.
Comparators have a few extra things to watch:
- Nulls. A comparator is not required to accept
null.ByNameComparatorthrowsNullPointerExceptionif an element isnull, and also if a name isnull. Handling nulls is the topic of a later chapter. - State. A comparator should not carry mutable state that changes its answers. If one sort calls it from several threads, as a parallel stream may, hidden state makes the result unpredictable.
- Mixed types.
comparehas typed parameters, but a rawComparatorcan receive an object of the wrong type. That raisesClassCastExceptionat run time.
Comparable and Comparator side by side
| Row | `Comparable<T>` | `Comparator<T>` |
|---|---|---|
| Package | `java.lang` | `java.util` |
| Method | `int compareTo(T other)` | `int compare(T a, T b)` |
| Where the code lives | Inside the class being sorted | In a separate class, lambda or constant |
| Number of orderings | One per class | As many as you write |
| Needs access to the class source | Yes | No |
| Used automatically by | `Collections.sort(list)`, `TreeSet`, `TreeMap`, `PriorityQueue` | Only when you pass it in |
A Comparator is an example of the strategy pattern. The sorting code stays the same, and the ordering strategy is a value you hand to it.
Summary of what to remember
Comparator<T>defines an ordering outside the type it orders, throughcompare(T, T).- The sign rules match
compareTo: negative means first, zero means tie, positive means second. - Passing a comparator to
sort,TreeSetorTreeMapreplaces the natural ordering. Passingnullselects the natural ordering. - A tie result of 0 means "same position" to sorted collections, which may drop the second element.
- The same contract applies to comparators as to
compareTo, and a comparator does not have to handlenull.
Exercise
A list of strings should be sorted by length, shortest first. Write a named class ByLength that implements Comparator<String> for this. Then say what words.sort(new ByLength()) does with "pear" and "plum" if "pear" comes first in the list, and why.
Show answer
public class ByLength implements java.util.Comparator<String> { @Override public int compare(String a, String b) { return Integer.compare(a.length(), b.length()); } } The method returns a negative number when a is shorter, zero when the lengths are equal and a positive number when a is longer. "pear" and "plum" both have length 4, so compare returns 0 and they tie. List.sort is stable, so "pear" stays before "plum". Using a - b on the lengths would also work for small values, but Integer.compare is the safe habit.
Exercise
You add the elements "pear", "plum" and "fig" to new TreeSet<>(new ByLength()). How many elements does the set hold, and which one is missing?
Show answer
The set holds two elements. "pear" and "plum" compare as 0 under ByLength, so the TreeSet treats them as the same element and keeps only the first one added, "pear". The set contains "fig" and "pear". The TreeSet uses the comparator, not equals, to decide whether two elements are duplicates.