Easy java core-java

What is the difference between Comparable and Comparator?

The 30 second answer

Comparable defines a class's natural order inside the class itself, with one compareTo method, like String sorting alphabetically. Comparator is a separate object that defines any other order, so I can have many: by salary, by name, reversed. Since Java 8 I build them with Comparator.comparing, thenComparing and reversed. TreeMap, TreeSet and sort use whichever I give them, and the order should be consistent with equals.

<!-- level: 1 --> <!-- must_know: true -->

ComparableComparator
Packagejava.langjava.util
MethodcompareTo(T other)compare(T a, T b)
WhereInside the classOutside the class
How manyOne natural orderAs many as you like
record Emp(String name, int salary) { }

List<Emp> list = new ArrayList<>(List.of(
        new Emp("Sara", 900), new Emp("Ali", 1200), new Emp("Reza", 900)));

list.sort(Comparator.comparingInt(Emp::salary).reversed()
                    .thenComparing(Emp::name));
// [Emp[name=Ali, salary=1200], Emp[name=Reza, salary=900], Emp[name=Sara, salary=900]]
  • compareTo and compare return a negative number, zero or a positive number for less than, equal and greater than.
  • The Comparable Javadoc strongly recommends that the natural order be consistent with equals, because sorted sets and maps use compareTo instead of equals to decide whether two elements are the same.
  • Avoid a - b in a comparator; it can overflow. Use Integer.compare or Comparator.comparingInt.
Sources (2)
  1. Javadoc: java.lang.Comparabledocs.oracle.com
  2. Javadoc: java.util.Comparatordocs.oracle.com