Lesson 27 / 38
Comparable vs Comparator
Give your class one natural ordering with Comparable, or define as many custom orderings as you need with Comparator, and combine them fluently.
One ordering vs many
Comparable<T> is implemented by the class itself and defines its single "natural" ordering via compareTo. Comparator<T> is a separate object that defines an ordering from the outside — you can have as many comparators as you need for the same class.
Comparable
Return negative/zero/positive to mean less-than/equal/greater-than. This lets Collections.sort(list) and TreeSet work with no extra arguments.
class Employee implements Comparable<Employee> {
int age;
public int compareTo(Employee other) {
return Integer.compare(this.age, other.age);
}
}
Collections.sort(employees); // sorted by ageComparator, fluently
Comparator.comparing(...) builds a comparator from a key extractor; chain .thenComparing(...) for tie-breaks and .reversed() to flip the order — all without touching the Employee class.
Comparator<Employee> byNameThenAge =
Comparator.comparing((Employee e) -> e.name)
.thenComparing(e -> e.age);
employees.sort(byNameThenAge.reversed());