What is the difference between Comparable and Comparator?

7 minintermediatecomparablecomparatorsorting

Quick Answer

Comparable is implemented by the class itself to define a single, natural ordering via compareTo(); a class can have only one. Comparator is a separate, standalone strategy object (often a lambda) defining an ordering via compare(a, b); you can create as many Comparators as needed, including for classes you can't modify.

Detailed Answer

Both drive sorting/ordering, but from different places:

  • Comparable<T>: implemented by the class being sorted, defining its single "natural" ordering via int compareTo(T other). Used by Collections.sort(list) / Arrays.sort(arr) with no extra argument, and by sorted collections (TreeSet, TreeMap) by default.
class Employee implements Comparable<Employee> {
    int salary;
    public int compareTo(Employee other) { return Integer.compare(salary, other.salary); }
}
Collections.sort(employees); // uses compareTo
  • Comparator<T>: a separate object (often a lambda or method reference) representing one specific ordering strategy, passed explicitly where needed. A class can have unlimited comparators, including ones defined outside the class entirely — useful for sorting classes you don't own, or supporting multiple orderings.
Comparator<Employee> byName = Comparator.comparing(e -> e.name);
Comparator<Employee> bySalaryDesc = Comparator.comparingInt((Employee e) -> e.salary).reversed();
employees.sort(byName.thenComparing(bySalaryDesc));

Rule of thumb: implement Comparable for the one obvious, canonical ordering of a type (e.g., Integer's natural numeric order); use Comparator for anything situational, alternative, or external to the class.