java.util.Comparator<T> is a functional interface that defines an ordering for objects of type T through a single method, int compare(T a, T b). It returns a negative number when a sorts before b, zero when they are equal for sorting, and a positive number when a sorts after b. You pass a comparator to List.sort, Collections.sort, Arrays.sort, TreeMap, TreeSet or Stream.sorted to sort by any rule you like without changing the class itself.
Since Java 8 you rarely write a comparator class by hand. Static factories such as Comparator.comparing and the default method thenComparing build clear, null-safe orderings in one line.
compare contractcomparing and thenComparingcompare contractcompare(a, b) must behave consistently, or sorting can throw IllegalArgumentException: Comparison method violates its general contract!. The rules are:
sign(compare(a, b)) equals -sign(compare(b, a)).a is before b and b is before c, then a is before c.compare(a, b) is zero, a and c compare the same way as b and c.compare(a, b) == 0 should match a.equals(b). If it does not, sorted sets and maps treat the elements as duplicates based on the comparator, not on equals.Never subtract values to compare them (a.age - b.age), because integer overflow can flip the sign. Use Integer.compare(a, b) or the factory methods below.
Comparable<T> | Comparator<T> | |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T other) | compare(T a, T b) |
| Where it lives | Inside the class itself | In a separate object or lambda |
| Number of orderings | One natural order | As many as you need |
| Works on classes you cannot edit | No | Yes |
Implement Comparable for the one obvious natural order (for example numbers or dates), and use Comparator for every other sort.
comparing and thenComparingThe examples below use a record, available since Java 16 and standard in Java 21 and 25 LTS:
The list is sorted by age ascending, and people with the same age are ordered by name in reverse. comparingInt avoids boxing for primitive keys; comparing works for any Comparable key such as String or LocalDate.
| Method | What it does |
|---|---|
compare(a, b) | The single abstract method you implement |
Comparator.comparing(keyExtractor) | Orders by a key taken from each object |
comparingInt, comparingLong, comparingDouble | Primitive versions that avoid boxing |
thenComparing(...) | Breaks ties with a second comparator or key |
reversed() | Returns the opposite order |
Comparator.naturalOrder(), reverseOrder() | Use compareTo, or the reverse of it |
nullsFirst(c), nullsLast(c) | Wrap a comparator so null elements are allowed |
reversed() applies to the comparator before it, so write it at the right place in a chain. Use nullsLast when keys can be null; without it a null key throws NullPointerException:
Without nullsLast, the null element would make the sort throw a NullPointerException. Sorting is stable, so equal elements keep their original relative order.
A lambda works wherever a comparator is needed, since the interface has one abstract method (equals is also declared but is inherited from Object):
Write a named class only when the comparator has configuration or state, or when you need to reuse and test it on its own.
TreeSet and TreeMap use the comparator for ordering and for uniqueness. Two elements that compare as zero are treated as the same key, so a comparator that ignores a field also removes elements that differ only in that field.
"dog" is dropped because its length equals that of "cat". Add thenComparing(Comparator.naturalOrder()) to keep both.
Comparator and Comparable?Comparable gives a class one built-in natural order through compareTo. Comparator is a separate object that defines any order you want, so you can sort the same class several ways.
List.sort and Collections.sort use TimSort, a stable merge-based algorithm. Arrays.sort on object arrays uses it too, so ties keep their original order.
Call reversed() on a comparator, or use Comparator.reverseOrder() for natural order. For a key extractor, Comparator.comparing(Person::age, Comparator.reverseOrder()) is the clearest form.
Your compare is inconsistent, often from subtracting values, mixing field checks, or comparing floating-point values with < incorrectly. Use Integer.compare, Double.compare and the factory methods.
Comparator<T> defines a custom ordering through compare(a, b).Comparator.comparing(...), thenComparing(...) and reversed() over hand-written classes.nullsFirst or nullsLast for nullable keys, and keep the order consistent with equals in sorted sets and maps.