Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Collections

The Comparator interface

Reference for java.util.Comparator: define custom orderings with lambdas, chain tie-breakers, reverse, handle nulls and sort lists and arrays.

A Comparator<T> is an object that decides how two values of type T are ordered. Its single abstract method, compare(a, b), returns a negative number when a comes first, zero when they are equivalent and a positive number when b comes first. Because it is a functional interface, you usually write one as a lambda or build it from the factory methods in Comparator.comparing().

Use a comparator when a class has no natural order (it does not implement Comparable), when you want a different order from the natural one, or when you need several orders for the same class. Comparators are accepted by List.sort(), Arrays.sort(), Collections.sort(), TreeMap, TreeSet, PriorityQueue and Stream.sorted().

Java
Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length());
list.sort(byLength.thenComparing(Comparator.naturalOrder()));

Try it

Java Writing and combining comparators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Nulls, records and a common bug

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
    // plus default and static helpers
}
Method Description
int compare(T a, T b) The ordering function.
Comparator<T> reversed() Reverses this comparator.
thenComparing(Comparator) Tie-breaker used when this comparator returns 0. Variants take a key extractor, with or without a key comparator.
thenComparingInt/Long/Double(...) Tie-breakers on primitive keys, without boxing.
static comparing(...), comparingInt/Long/Double(...) Build from a key extractor.
static naturalOrder(), reverseOrder() Orders by Comparable (reverse).
static nullsFirst(c), nullsLast(c) Wrap a comparator to allow null values.

Usage notes

  • The contract: compare must be antisymmetric (sign(compare(a,b)) == -sign(compare(b,a))), transitive and consistent. A broken comparator can make TimSort throw IllegalArgumentException: Comparison method violates its general contract!.
  • Never subtract to compare ints (a - b): overflow flips the sign. Use Integer.compare(), Double.compare() and friends.
  • Consistent with equals? Sorted sets and maps use the comparator, not equals(), to decide duplicates. In the first example "bb" is dropped because it compares as 0 with "aa".
  • Stability: List.sort(), Arrays.sort(Object[], c) and Stream.sorted() on ordered streams are stable, so equal elements keep their original order. Sorting primitive arrays has no comparator.
  • Reuse: comparators have no state, so a static final constant is safe to share between threads.
  • Natural order alternative: implement Comparable when there is one obvious order. See Comparable.
  • null comparator passed to sort() or a TreeMap constructor means natural ordering.
  • Serializable: a comparator stored in a TreeMap that you serialize must itself be Serializable.