java.util · java.base · since Java 1.2
Comparator
@FunctionalInterface
public interface Comparator<T>An external ordering strategy, transformed by Java 8 combinators (comparing, thenComparing, reversed, nullsFirst) into a tiny declarative sort language.
Key methods
int compare(T o1, T o2) | The sole abstract method — negative/zero/positive per the Comparable contract. |
static <T,U extends Comparable<? super U>> Comparator<T> comparing(Function<T,U> key) | Order by an extracted Comparable key. |
static <T,U> Comparator<T> comparing(Function<T,U> key, Comparator<U> keyComparator) | Order by an extracted key using an explicit key comparator. |
static <T> Comparator<T> comparingInt/comparingLong/comparingDouble(…) | Boxing-free primitive key comparators. |
default Comparator<T> thenComparing(Comparator<? super T> other) | Tie-breaker, applied only when the primary comparator returns 0. |
default Comparator<T> thenComparing(Function<? super T,U> key) | Tie-breaker by another extracted Comparable key. |
default Comparator<T> thenComparingInt/Long/Double(…) | Boxing-free tie-breakers. |
default Comparator<T> reversed() | Flip this comparator's order. |
static <T extends Comparable<? super T>> Comparator<T> naturalOrder() | The Comparable order, reified as a Comparator object. |
static <T extends Comparable<? super T>> Comparator<T> reverseOrder() | naturalOrder().reversed(), pre-built. |
static <T> Comparator<T> nullsFirst(Comparator<? super T>) | Sort nulls before non-nulls; pass null to use natural order for the rest. |
static <T> Comparator<T> nullsLast(Comparator<? super T>) | Sort nulls after non-nulls. |
Example
Comparator<Employee> byPay = Comparator.comparing(Employee::getDept)
.thenComparing(Employee::getSalary)
.reversed(); // within each dept, highest salary first; depts reverse-alphabetical
employees.sort(byPay);