The Comparator interface in Java defines a custom ordering for objects of a type, separate from the type itself. Its single abstract method, compare(a, b), returns a negative number, zero or a positive number when a is less than, equal to or greater than b. It lets you sort the same objects in many ways, such as by name, by age or by several fields, without changing the class.
Comparator lives in java.util and has been a functional interface since Java 8, which means you usually create one with a lambda or with the static factory methods instead of writing a class.
Comparable<T> gives a class one natural ordering by implementing compareTo. Comparator<T> is an external strategy, so you can have as many as you need.
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T other) | compare(T a, T b) |
| Where the order is defined | Inside the class | Outside the class |
| Number of orderings | One | Any number |
| Needs to modify the class | Yes | No |
Use Comparable for the one obvious natural order (numbers, dates, strings) and Comparator for everything else, or when you cannot edit the class.
Since Java 8 the preferred way to build a comparator is with Comparator.comparing and related methods.
The list is sorted by age ascending, then by name descending for equal ages. The useful building blocks are:
comparing(keyExtractor) and comparingInt, comparingLong, comparingDouble, which avoid boxing for primitives.thenComparing(...) to add tie-breakers.reversed() to flip an order, and Comparator.reverseOrder() or naturalOrder() for Comparable types.nullsFirst(...) and nullsLast(...) to handle null values safely.Before Java 8 you wrote an anonymous class, and a lambda is the modern equivalent.
Always use Integer.compare, Long.compare or Double.compare. Writing a.length() - b.length() looks equivalent but overflows for large or negative values and produces wrong results. Your comparator must also be consistent: if compare(a, b) is negative then compare(b, a) must be positive, and the relation must be transitive. A broken comparator can make List.sort throw IllegalArgumentException: Comparison method violates its general contract.
Real data contains missing values and mixed case. Combine the helpers to handle both.
String.CASE_INSENSITIVE_ORDER ignores case, and nullsLast moves null to the end instead of throwing NullPointerException. For locale-aware text sorting, use java.text.Collator as the comparator, because simple character comparison does not follow the alphabet rules of every language.
List.sort(comparator) and Collections.sort(list, comparator).Arrays.sort(array, comparator) for object arrays.Stream.sorted(comparator), Stream.min(comparator) and Stream.max(comparator).new TreeSet<>(comparator), new TreeMap<>(comparator) and PriorityQueue.Be aware that a TreeSet or TreeMap treats two elements as duplicates when the comparator returns zero, even if equals says they differ. For predictable behaviour, keep the comparator consistent with equals or add a final tie-breaker such as an id.
Comparable defines one natural order inside the class. Comparator defines an order outside the class, and you can supply many of them.
Call reversed() on a comparator, or use Comparator.reverseOrder() for naturally ordered types.
Chain thenComparing after the first comparator. Each later comparator is used only when the earlier ones return zero.
Wrap the key comparator in Comparator.nullsFirst(...) or Comparator.nullsLast(...).
Comparator separates ordering from the objects being ordered. Build comparators with comparing, thenComparing, reversed and the null-handling helpers, use Integer.compare instead of subtraction, and keep the ordering consistent so sorting and sorted collections behave correctly.