Comparable and Comparator

Java sorts objects through two interfaces: Comparable gives a class its one natural order, and Comparator describes any other order from outside the class. This page explains the contract both must follow, builds orders with the Comparator factory methods, handles nulls, shows the bugs that break sorting and sorted collections, and measures what boxing in comparators costs.

Contents

Two interfaces for ordering

Sorting algorithms and sorted collections never look at fields themselves. They only ask one question about two objects: which comes first? That question is answered by an int: negative if the first comes before the second, zero if they are equal in this order, positive if the first comes after.

  • Comparable<T> (Java 1.2) is implemented by a class to define its natural order with compareTo(T other). String, the number wrappers, LocalDate and BigDecimal all have one. Collections.sort(list), TreeSet and TreeMap use it when no comparator is given.
  • Comparator<T> (Java 1.2) is a separate object with compare(a, b). A class can have any number of comparators, and they can be written for classes you cannot change. Since Java 8 it has factory and combinator methods such as comparing, thenComparing, reversed and nullsFirst.

Both must follow the same contract: the sign must flip when the arguments are swapped, the order must be transitive (if a < b and b < c then a < c), and elements that compare as 0 must compare the same way with everything else. The contract also recommends, but does not require, that compareTo returns 0 exactly when equals is true.

Comparator factory methods
MethodSinceBest for
Comparator.comparing(keyExtractor)Java 8Ordering by one property
comparingInt, comparingLong, comparingDoubleJava 8Primitive keys, without boxing
thenComparing(...)Java 8Tie-breakers
reversed(), Comparator.reverseOrder()Java 8Descending order
nullsFirst, nullsLastJava 8Lists that contain null
Integer.compare, Long.compareJava 7Writing compareTo by hand
String.CASE_INSENSITIVE_ORDER, CollatorJava 1.2, 1.1Text; see string comparison

Every program on this page was run on JDK 21.

Comparable: a natural order for your own class

Version numbers are a good example, because their natural order is not the order of their text: 2.10 comes after 2.9, and 10.0 after both.

Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NaturalOrder {

    // A class opts in to a natural order by implementing Comparable
    record Version(int major, int minor) implements Comparable<Version> {

        @Override
        public int compareTo(Version other) {
            int byMajor = Integer.compare(major, other.major);
            return byMajor != 0 ? byMajor : Integer.compare(minor, other.minor);
        }

        @Override
        public String toString() {
            return major + "." + minor;
        }
    }

    public static void main(String[] args) {
        List<Version> versions = new ArrayList<>(List.of(
                new Version(2, 10), new Version(1, 4), new Version(2, 9), new Version(10, 0)));

        Collections.sort(versions);
        System.out.println("sorted:  " + versions);

        // Strings sort by character code, which is why "10.0" text would come before "2.9"
        List<String> asText = new ArrayList<>(List.of("2.10", "1.4", "2.9", "10.0"));
        Collections.sort(asText);
        System.out.println("as text: " + asText);

        System.out.println("compare 1.4 to 2.9: " + new Version(1, 4).compareTo(new Version(2, 9)));
        System.out.println("max:     " + Collections.max(versions));
    }
}

Output:

Output
sorted:  [1.4, 2.9, 2.10, 10.0]
as text: [1.4, 10.0, 2.10, 2.9]
compare 1.4 to 2.9: -1
max:     10.0
  • compareTo compares the major numbers first and only looks at the minor numbers on a tie, the pattern for any multi-part key.
  • Integer.compare returns -1, 0 or 1 safely for any two values. Subtraction can overflow, as a later section shows.
  • Sorting the same versions as strings gives 1.4, 10.0, 2.10, 2.9, because strings compare character by character and '1' comes before '2'.
  • Once a class is Comparable, Collections.max, TreeSet and streams' sorted() all use its order without extra code.

The generic parameter matters: implementing Comparable<Version> rather than the raw Comparable lets the compiler reject comparisons with unrelated types, and records make such small value classes short to write. A natural order should also agree with equals, so that sorted and hashed collections treat the same objects as duplicates. Give a class a natural order only when there is one obvious order. For anything else, such as sorting employees by salary, use a Comparator.

Building comparators with comparing and thenComparing

The employee list has ties in both department and salary, so each step of the chain decides some of the order.

Java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ComparatorChains {

    record Employee(String name, String dept, int salary) {
    }

    public static void main(String[] args) {
        List<Employee> staff = new ArrayList<>(List.of(
                new Employee("Priya", "Eng", 120),
                new Employee("Arjun", "Ops", 90),
                new Employee("Mei", "Eng", 150),
                new Employee("Tom", "Ops", 90),
                new Employee("Ana", "Eng", 120)));

        // Department A-Z, then salary high to low, then name A-Z
        Comparator<Employee> order = Comparator
                .comparing(Employee::dept)
                .thenComparing(Employee::salary, Comparator.reverseOrder())
                .thenComparing(Employee::name);

        staff.sort(order);
        staff.forEach(e -> System.out.println(e.dept() + "  " + e.salary() + "  " + e.name()));

        // comparingInt avoids boxing each salary into an Integer
        Comparator<Employee> bySalary = Comparator.comparingInt(Employee::salary);
        System.out.println("lowest paid: " + staff.stream().min(bySalary).orElseThrow().name());

        // reversed() flips the WHOLE chain built so far
        staff.sort(order.reversed());
        System.out.println("fully reversed first: " + staff.get(0).name());
    }
}

Output:

Output
Eng  150  Mei
Eng  120  Ana
Eng  120  Priya
Ops  90  Arjun
Ops  90  Tom
lowest paid: Arjun
fully reversed first: Tom
  • The chain reads like the requirement: department A to Z, then salary from high to low, then name. Ana and Priya both earn 120 in Eng, so the name decides.
  • thenComparing(key, Comparator.reverseOrder()) reverses only that step.
  • comparingInt takes an int key directly; comparing would box each salary into an Integer for every comparison.
  • reversed() applies to the whole chain built so far, not just the last step, so the fully reversed order starts with Ops and Tom. Put reversed() inside a step when only that step should be descending.

Nulls, overflow and duplicates in sorted sets

Four small cases cover the mistakes that show up most often in code reviews: a list with nulls, a subtraction comparator, a comparator that treats different elements as equal, and mixed-case text.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;

public class NullsAndPitfalls {

    public static void main(String[] args) {
        // 1. nullsFirst / nullsLast wrap a comparator so null elements do not throw
        List<String> cities = new ArrayList<>(Arrays.asList("Pune", null, "Austin", null, "Oslo"));
        cities.sort(Comparator.nullsLast(Comparator.naturalOrder()));
        System.out.println("nullsLast:  " + cities);

        // 2. Subtraction as a comparator overflows for large values
        Comparator<Integer> bySubtraction = (a, b) -> a - b;
        int wrong = bySubtraction.compare(Integer.MIN_VALUE, 1);
        int right = Integer.compare(Integer.MIN_VALUE, 1);
        System.out.println("MIN_VALUE vs 1, subtraction: " + wrong + "  Integer.compare: " + right);

        // 3. A TreeSet treats compare() == 0 as "same element" and drops it
        Comparator<String> byLength = Comparator.comparingInt(String::length);
        TreeSet<String> set = new TreeSet<>(byLength);
        set.addAll(List.of("kiwi", "pear", "fig", "plum"));
        System.out.println("TreeSet by length: " + set);

        // Adding a tie-breaker keeps every distinct element
        TreeSet<String> fixed = new TreeSet<>(byLength.thenComparing(Comparator.naturalOrder()));
        fixed.addAll(List.of("kiwi", "pear", "fig", "plum"));
        System.out.println("with tie-breaker:  " + fixed);

        // 4. Case-insensitive order for text
        List<String> names = new ArrayList<>(List.of("bob", "Alice", "carol", "Bob"));
        names.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println("case-insensitive:  " + names);
    }
}

Output:

Output
nullsLast:  [Austin, Oslo, Pune, null, null]
MIN_VALUE vs 1, subtraction: 2147483647  Integer.compare: -1
TreeSet by length: [fig, kiwi]
with tie-breaker:  [fig, kiwi, pear, plum]
case-insensitive:  [Alice, bob, Bob, carol]
  • Natural order throws NullPointerException on a null element. nullsLast(naturalOrder()) puts the nulls at the end and sorts the rest normally.
  • (a, b) -> a - b looks like a compact comparator, but Integer.MIN_VALUE - 1 overflows to 2,147,483,647, so the smallest value is reported as larger than 1. Always use Integer.compare or comparingInt.
  • A TreeSet uses the comparator, not equals, to decide whether an element is already present. Ordered by length only, pear and plum were dropped because they have the same length as kiwi. A tie-breaker keeps all four.
  • String.CASE_INSENSITIVE_ORDER sorts bob and Bob together; between them the original order is kept, because sorting is stable.

When the contract is broken

A comparator that breaks the contract does not always fail loudly. The program shows four ways it goes wrong, from a set that holds fewer elements than expected to a sort that throws.

Java
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

public class ContractBreaks {

    public static void main(String[] args) {
        // compareTo inconsistent with equals: BigDecimal 2.0 and 2.00
        List<BigDecimal> amounts = List.of(new BigDecimal("2.0"), new BigDecimal("2.00"));
        Set<BigDecimal> hash = new HashSet<>(amounts);
        Set<BigDecimal> tree = new TreeSet<>(amounts);
        System.out.println("HashSet size " + hash.size() + ", TreeSet size " + tree.size()
            + ", equals: " + amounts.get(0).equals(amounts.get(1))
            + ", compareTo: " + amounts.get(0).compareTo(amounts.get(1)));

        // A comparator that never returns 0 and is not antisymmetric
        Comparator<Integer> neverEqual = (a, b) -> a < b ? -1 : 1;
        System.out.println("neverEqual.compare(5, 5) = " + neverEqual.compare(5, 5)
            + " (should be 0)");

        // A comparator that breaks transitivity: TimSort may detect it and throw
        Random random = new Random(42);
        List<Integer> data = new ArrayList<>();
        for (int i = 0; i < 2000; i++) {
            data.add(random.nextInt(100));
        }
        Comparator<Integer> broken = (a, b) -> Math.abs(a - b) < 10 ? 0 : Integer.compare(a, b);
        try {
            Collections.sort(data, broken);
            System.out.println("broken comparator: sorted without an error, order is unreliable");
        } catch (IllegalArgumentException e) {
            System.out.println("broken comparator: " + e.getMessage());
        }

        // Comparing mutable fields: changing an element after insertion corrupts a TreeSet
        List<int[]> boxes = new ArrayList<>();
        TreeSet<int[]> byFirst = new TreeSet<>(Comparator.comparingInt(a -> a[0]));
        for (int i : new int[] {5, 1, 9}) {
            int[] box = {i};
            boxes.add(box);
            byFirst.add(box);
        }
        boxes.get(0)[0] = 20;                    // the element that was 5 is now 20
        System.out.println("contains the changed element? " + byFirst.contains(boxes.get(0))
            + ", first=" + byFirst.first()[0] + ", last=" + byFirst.last()[0]);
    }
}

Output:

Output
HashSet size 2, TreeSet size 1, equals: false, compareTo: 0
neverEqual.compare(5, 5) = 1 (should be 0)
broken comparator: Comparison method violates its general contract!
contains the changed element? true, first=1, last=9
  • BigDecimal's natural order is inconsistent with equals: 2.0 and 2.00 compare as 0 but are not equals, so a HashSet keeps both and a TreeSet keeps one. The BigDecimal page explains why.
  • A comparator that never returns 0 says that 5 comes after 5, which breaks the sign rule and makes contains and remove on sorted collections unreliable.
  • The "within 10 counts as equal" comparator is not transitive: 0 equals 9 and 9 equals 18, but 0 is less than 18. On 2,000 elements, Collections.sort, which uses TimSort, detected the inconsistency and threw IllegalArgumentException with "Comparison method violates its general contract!". On other data it may finish silently with a wrong order.
  • A sorted collection places each element when it is added. Changing the field the comparator reads afterwards leaves the element in the wrong place: the set holds 20 but last() reports 9. Compare only on fields that do not change while the element is in the collection.

Where comparators are used

The same comparator object works everywhere Java needs an order: stream operations, collectors, priority queues and sorted maps. The tasks have duplicate priorities, so the tie-breaker matters in each case.

Java
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class WhereUsed {

    record Task(String name, int priority) {
    }

    public static void main(String[] args) {
        List<Task> tasks = List.of(new Task("deploy", 2), new Task("fix bug", 1),
            new Task("write docs", 3), new Task("review", 1));
        Comparator<Task> byPriority = Comparator.comparingInt(Task::priority)
            .thenComparing(Task::name);

        // Streams
        System.out.println("sorted:     "
            + tasks.stream().sorted(byPriority).map(Task::name).toList());
        System.out.println("max:        " + tasks.stream().max(byPriority).orElseThrow().name());
        Map<Integer, String> firstPerPriority = tasks.stream().collect(Collectors.groupingBy(
            Task::priority, TreeMap::new, Collectors.collectingAndThen(
                Collectors.minBy(Comparator.comparing(Task::name)), t -> t.orElseThrow().name())));
        System.out.println("minBy name per priority: " + firstPerPriority);

        // A priority queue always hands out the smallest element first
        PriorityQueue<Task> queue = new PriorityQueue<>(byPriority);
        queue.addAll(tasks);
        StringJoiner order = new StringJoiner(" | ");
        while (!queue.isEmpty()) {
            order.add(queue.poll().name());
        }
        System.out.println("PriorityQueue: " + order);

        // A sorted map keyed by a comparator
        TreeMap<String, Integer> byLengthThenText = new TreeMap<>(
            Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
        for (Task t : tasks) {
            byLengthThenText.put(t.name(), t.priority());
        }
        System.out.println("TreeMap:    " + byLengthThenText);

        // Comparator.naturalOrder and reverseOrder for Comparable types
        System.out.println("max string: " + List.of("pear", "apple", "fig").stream()
            .max(Comparator.naturalOrder()).orElseThrow());
    }
}

Output:

Output
sorted:     [fix bug, review, deploy, write docs]
max:        write docs
minBy name per priority: {1=fix bug, 2=deploy, 3=write docs}
PriorityQueue: fix bug | review | deploy | write docs
TreeMap:    {deploy=2, review=1, fix bug=1, write docs=3}
max string: pear
  • sorted(cmp), max(cmp) and min(cmp) on streams take a comparator directly. With the tie-breaker, fix bug comes before review, both priority 1.
  • Collectors.minBy and maxBy find the extreme element within each group of a groupingBy; see the groupingBy page.
  • A PriorityQueue built with the comparator always returns the smallest remaining element from poll(), which is how task schedulers work. Its iteration order is not sorted; only poll is. The PriorityQueue page explains the heap behind it.
  • A TreeMap keeps its keys in comparator order, here shortest name first, with alphabetical order breaking ties.
  • Comparator.naturalOrder() turns a Comparable type's own order into a comparator, for APIs that require one.

What comparators cost

A sort calls the comparator millions of times, so small overheads multiply. The program sorts 500,000 orders with four comparators, each on a fresh copy, keeping the fastest of three runs.

Java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

public class ComparatorSpeed {

    record Order(String customer, int amount, long id) {
    }

    public static void main(String[] args) {
        Random random = new Random(9);
        List<Order> orders = new ArrayList<>();
        for (int i = 0; i < 500000; i++) {
            orders.add(new Order("c" + random.nextInt(1000), random.nextInt(10000), i));
        }
        System.out.printf("sort %,d orders%n", orders.size());
        time("comparing(Order::amount) (boxes)", orders, Comparator.comparing(Order::amount));
        time("comparingInt(Order::amount)", orders, Comparator.comparingInt(Order::amount));
        time("lambda Integer.compare", orders, (a, b) -> Integer.compare(a.amount(), b.amount()));
        time("customer, then amount", orders, Comparator.comparing(Order::customer)
            .thenComparingInt(Order::amount));
    }

    // Best of 3 runs, each on a fresh copy of the unsorted list
    static void time(String name, List<Order> input, Comparator<Order> cmp) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            List<Order> copy = new ArrayList<>(input);
            long t0 = System.nanoTime();
            copy.sort(cmp);
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("  %-34s %6.1f ms%n", name, best / 1e6);
    }
}

Output (2-CPU Linux machine, JDK 21; differences of a few milliseconds are noise):

Output
sort 500,000 orders
  comparing(Order::amount) (boxes)    185.1 ms
  comparingInt(Order::amount)         155.1 ms
  lambda Integer.compare              153.4 ms
  customer, then amount               298.9 ms
  • comparing(Order::amount) boxes the int keys into Integer objects and was the slowest of the single-key versions. comparingInt and a hand-written lambda avoid boxing; the JIT often removes much of the boxing anyway, so the gap is modest.
  • A two-step chain that compares strings first took longer, because string comparison is more work and most comparisons are decided by the customer name.

The differences are small next to the cost of a wrong comparator. Choose the clearest comparator, and prefer comparingInt and friends for primitive keys.

Which to use

Choosing an ordering approach
SituationUse
The class has one obvious orderImplement Comparable
Any other order, or a class you cannot changeA Comparator
Order by a propertyComparator.comparing(Type::getter)
Primitive keycomparingInt, comparingLong, comparingDouble
Tie-breakersthenComparing
Descendingreversed() for the whole chain, reverseOrder() for one step
Nulls in the datanullsFirst or nullsLast
Writing compareTo by handInteger.compare, never subtraction
Keys in a TreeSet or TreeMapA comparator consistent with equals, on fields that do not change

For sorting lists, arrays and streams with these comparators, see sorting collections.