Hiprup

What is the difference between Comparable and Comparator?

Both define ordering, but in different places.

Comparable — the class itself implements compareTo(), defining its natural ordering (e.g., String, Integer). Single ordering per class.

Comparator — an external ordering supplied via compare(). Lets you define many orderings without modifying the class. Often written as a lambda or built with Comparator.comparing(...).

UseComparable when there's one obvious order; Comparator when you need flexibility or work with classes you don't own.

// Comparable - natural ordering
public class Employee implements Comparable<Employee> {
    private String name;
    private int age;
    private double salary;

    @Override
    public int compareTo(Employee other) {
        return this.name.compareTo(other.name); // Natural ordering by name
    }
}

// Comparator - custom orderings
Comparator<Employee> bySalary = Comparator.comparingDouble(Employee::getSalary);
Comparator<Employee> byAge = Comparator.comparingInt(Employee::getAge);
Comparator<Employee> byNameThenAge = Comparator.comparing(Employee::getName)
                                               .thenComparingInt(Employee::getAge);
Comparator<Employee> bySalaryDesc = Comparator.comparingDouble(Employee::getSalary)
                                               .reversed();

// Usage
List<Employee> employees = getEmployees();
Collections.sort(employees);              // Uses Comparable (by name)
employees.sort(bySalary);                  // Uses Comparator (by salary)
employees.sort(bySalaryDesc);              // Descending salary
employees.sort(byNameThenAge);             // Multi-field sort

Employee implements Comparable with natural ordering by name. Multiple Comparators provide alternative orderings: by salary, by age, by name-then-age, and descending salary.

Comparator.comparing with method references creates concise comparators. thenComparing chains secondary sort criteria. reversed() inverts the ordering.

Know the difference: Comparable = natural ordering (one per class), Comparator = custom ordering (many possible). Show Java 8 Comparator factory methods (comparing, thenComparing, reversed).

These are more concise than anonymous classes.

What is the difference between Comparable and Comparator? | Hiprup