Part 09 / Topic 4 of 10
Comparable vs. Comparator: putting things in order
These solve the same problem — "which of these two is first?" — from two different places.
Comparable<T>is implemented by the class itself. It defines that class's one, single natural order. A class can only have one.Comparator<T>is written separately, from outside the class. You can write as many as you like, for as many different orderings as you need, without changing the class at all.
Real-world example: a school's gradebook, ranking students by total marks.
class Student implements Comparable<Student> {
final String name;
final int maths;
final int science;
int total() { return maths + science; }
@Override
public int compareTo(Student other) {
return Integer.compare(other.total(), this.total()); // highest total first
}
}
compareTo must return a negative number if this comes first, zero if they are equal, and a positive number if other comes first — Integer.compare(a, b) does exactly this for two ints, so you rarely write the </> comparisons by hand.
List<Student> gradebook = ...;
gradebook.sort(null); // null comparator -> fall back to the natural order: compareTo()
Asha (maths=91, science=84, total=175)
Ravi (maths=78, science=95, total=173)
Meera (maths=88, science=85, total=173)
Kabir (maths=91, science=82, total=173)
Notice the three students tied at 173 keep their original list order (Ravi, Meera, Kabir): List.sort is a stable sort — it never reorders elements that compare as equal.
Comparator: any order, from outside the class
Comparator.comparing(keyExtractor) builds a comparator from a lambda that pulls out the field to compare by. Chain .reversed() and .thenComparing(...) to build richer orders without writing a single if.
Comparator<Student> byTotalThenName = Comparator
.comparingInt(Student::total).reversed()
.thenComparing(s -> s.name);
gradebook.sort(byTotalThenName);
Asha (maths=91, science=84, total=175)
Kabir (maths=91, science=82, total=173)
Meera (maths=88, science=85, total=173)
Ravi (maths=78, science=95, total=173)
The three-way tie from before is now broken alphabetically (Kabir, Meera, Ravi), because thenComparing only runs when the comparator before it says "equal." Comparator.comparingInt/comparingDouble/comparingLong avoid boxing an int/double/long into an Integer/Double/Long just to compare it — prefer them over the generic Comparator.comparing for primitive fields.
| Need | Use |
|---|---|
| The class has one obvious, permanent order (an ID, a natural ranking) | Comparable, implemented once on the class |
| You need a different order depending on the situation (by name here, by score there) | One or more Comparators, written outside the class |
| You cannot change the class at all (it is from a library) | Comparator — it is the only option |
Full program: examples/ComparableAndComparator.java.
Done here? The practice set for Part 9 — including the solutions — is on the part page.