Comparator in Java

Comparator defines an external, reusable ordering for objects, enabling multiple sort orders, sorting of classes you do not own, and lambda-based chaining.

Comparator<T> is a functional interface in java.util with the single method int compare(T o1, T o2). Unlike Comparable (which is implemented by the class itself to define its natural ordering), a Comparator is a separate strategy object that can be passed to sorting methods and collection constructors. This makes it possible to sort the same type of objects in multiple different ways, to sort classes you do not own, or to compose complex sort orders from simple building blocks.

Comparator vs Comparable

Aspect Comparable Comparator
Where defined Inside the class Outside the class
Method compareTo(T other) compare(T o1, T o2)
Number of orderings One (natural ordering) Unlimited
Modifiable Requires class change No class change needed
Lambda-friendly No Yes (@FunctionalInterface)
Used by default in Collections.sort, TreeSet Collections.sort(list, cmp), TreeSet(cmp)

Key API Methods (Java 8+)

Comparator was given rich static and default methods in Java 8:

Method Description
Comparator.comparing(keyExtractor) Creates comparator from key extractor
Comparator.comparingInt/Long/Double Primitive-safe variants
thenComparing(...) Chains a secondary comparator
reversed() Inverts the order
naturalOrder() Returns comparator based on natural order
reverseOrder() Reverses natural order
nullsFirst(cmp) / nullsLast(cmp) Wraps comparator to handle null

Examples

Multiple sort orders with Comparator chains

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

public class ComparatorChaining {
    record Product(String name, String category, double price) {}

    public static void main(String[] args) {
        List<Product> products = new ArrayList<>(List.of(
            new Product("Widget",   "Hardware", 9.99),
            new Product("Gadget",   "Software", 24.99),
            new Product("Gizmo",    "Hardware", 9.99),
            new Product("Thingamajig", "Software", 14.99)
        ));

        // Sort: category ascending, then price ascending, then name ascending
        Comparator<Product> byCategory = Comparator.comparing(Product::category);
        Comparator<Product> byCategoryThenPrice =
            byCategory.thenComparingDouble(Product::price)
                      .thenComparing(Product::name);

        products.sort(byCategoryThenPrice);
        products.forEach(p ->
            System.out.printf("%-15s %-10s $%.2f%n", p.name(), p.category(), p.price()));
        // Gizmo           Hardware   $9.99
        // Widget          Hardware   $9.99
        // Thingamajig     Software   $14.99
        // Gadget          Software   $24.99
    }
}

Sorting with nulls and reversed order

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class NullSafeSort {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Charlie", null, "Alice", null, "Bob");

        // nullsLast puts null entries after all non-null entries
        Comparator<String> nullsLast = Comparator.nullsLast(Comparator.naturalOrder());
        names.sort(nullsLast);
        System.out.println(names); // [Alice, Bob, Charlie, null, null]

        // Reversed natural order with nulls first
        Comparator<String> descNullsFirst =
            Comparator.nullsFirst(Comparator.<String>naturalOrder().reversed());
        names.sort(descNullsFirst);
        System.out.println(names); // [null, null, Charlie, Bob, Alice]
    }
}

Common Mistakes

  1. Subtraction-based compare. (a, b) -> a.getValue() - b.getValue() overflows for large or negative integers. Use Integer.compare(a.getValue(), b.getValue()) or Comparator.comparingInt(MyClass::getValue).

  2. Inconsistent compare method. If compare(a, b) > 0 but compare(b, a) > 0 (violating antisymmetry), TreeMap and sorting algorithms will produce wrong or non-deterministic results. Always test both orderings.

  3. Forgetting to handle null. A comparator that calls methods on its arguments will throw NullPointerException if either argument is null. Wrap with Comparator.nullsFirst(...) or Comparator.nullsLast(...) when null inputs are possible.

  4. Inconsistency with equals in sorted collections. A TreeSet using a Comparator that returns 0 for two objects where equals is false will treat them as duplicates and silently discard one, violating the Set contract.

  5. Creating a new Comparator instance in a hot loop. Comparators built with lambdas are lightweight, but avoid creating them inside tight loops where a single shared constant would serve better. Declare them as static final fields.

Best Practices

  • Use Comparator.comparing(keyExtractor) and thenComparing chains — they are readable, null-safe in the key extraction, and overflow-free.
  • Declare reusable comparators as public static final constants on the relevant class.
  • Use nullsFirst / nullsLast when the data may contain null entries.
  • Keep comparators consistent with equals when they are used in sorted sets or maps.
  • Prefer passing a Comparator explicitly over relying on natural ordering when the sort key is not obvious to the reader.

Interview Questions

1. What is the difference between Comparable and Comparator?

Comparable is implemented by the class itself to define its single natural ordering. Comparator is an external strategy object that defines one of many possible orderings. Use Comparable when the class has one obvious natural order; use Comparator when multiple orderings are needed or when you cannot modify the class.

2. How do you chain multiple sort criteria in Java 8+?

Use Comparator.comparing(firstKey).thenComparing(secondKey).thenComparing(thirdKey). Each thenComparing is applied only when the previous criterion produces a tie (returns 0). For primitives, use thenComparingInt, thenComparingLong, or thenComparingDouble to avoid boxing.

3. Why is the subtraction trick for compare dangerous?

Integer subtraction overflows when values are at opposite extremes of the int range. For example, Integer.MIN_VALUE - 1 wraps to Integer.MAX_VALUE, making compare(MIN_VALUE, 1) return a large positive number, which incorrectly says MIN_VALUE > 1. Use Integer.compare(a, b) or Comparator.comparingInt(...).

4. How do you sort in reverse order using Comparator?

Call .reversed() on any comparator, or use Comparator.reverseOrder() for natural ordering: list.sort(Comparator.reverseOrder()). For descending salary: Comparator.comparingInt(Employee::getSalary).reversed().

5. How do you handle null values in a Comparator?

Wrap with Comparator.nullsFirst(comparator) to sort nulls before all other elements, or Comparator.nullsLast(comparator) to sort them after. These wrappers prevent NullPointerException and cleanly define where nulls appear.

6. Can Comparator be used with TreeMap?

Yes. Pass the Comparator to the TreeMap constructor: new TreeMap<>(myComparator). The tree uses this comparator for all insertions, lookups, and ordering decisions. The comparator should be consistent with equals to satisfy the Map contract.

7. How does Comparator.comparing work internally?

Comparator.comparing(keyExtractor) returns a comparator that extracts a Comparable key from each element and delegates to key.compareTo(otherKey). Comparator.comparingInt(fn) uses Integer.compare on the results of calling fn, avoiding boxing. The resulting comparator is a lambda-backed implementation of Comparator<T>.

Summary

  • Comparator<T> is a functional interface for defining external, reusable sort strategies.
  • Use Comparator.comparing(...) and thenComparing(...) chains for readable, overflow-safe multi-key sorts.
  • Never use subtraction in compare — use Integer.compare, Long.compare, or Comparator.comparingInt.
  • Handle null values with Comparator.nullsFirst or Comparator.nullsLast.
  • Use Comparable for the single natural ordering; use Comparator for additional, external, or context-specific orderings.

Continue Learning

Previous: Comparable | Next: Collections Utility

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.