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().
Comparator<String> byLength = (a, b) -> Integer.compare(a.length(), b.length()); list.sort(byLength.thenComparing(Comparator.naturalOrder()));
Try it
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.
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
@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:
comparemust be antisymmetric (sign(compare(a,b)) == -sign(compare(b,a))), transitive and consistent. A broken comparator can makeTimSortthrowIllegalArgumentException: Comparison method violates its general contract!. - Never subtract to compare ints (
a - b): overflow flips the sign. UseInteger.compare(),Double.compare()and friends. - Consistent with
equals? Sorted sets and maps use the comparator, notequals(), to decide duplicates. In the first example"bb"is dropped because it compares as0with"aa". - Stability:
List.sort(),Arrays.sort(Object[], c)andStream.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 finalconstant is safe to share between threads. - Natural order alternative: implement
Comparablewhen there is one obvious order. See Comparable. nullcomparator passed tosort()or aTreeMapconstructor means natural ordering.- Serializable: a comparator stored in a
TreeMapthat you serialize must itself beSerializable.