Comparable vs Comparator and Sorting
Comparable defines an object's natural order inside the class; Comparator defines any number of external orders. Sorting objects by several fields with Comparator chains is a common live-coding task.
What you will learn
- Implement Comparable for natural ordering
- Build Comparators with comparing, thenComparing and reversed
- Keep compareTo consistent with equals
Key concepts
Comparable<T>
compareTo(T other) returns negative, zero or positive. Used by Collections.sort, TreeMap and TreeSet when no comparator is given.
Comparator<T>
compare(a, b) outside the class. Build with Comparator.comparing(Employee::salary).thenComparing(Employee::name).
Stable sort
List.sort and Collections.sort for objects use TimSort, which is stable: equal elements keep their relative order.
Step by step
Avoid subtraction in compare
// Wrong: overflows for large values
return a.age - b.age;
// Right
return Integer.compare(a.age, b.age);Examples
Sort employees by department, then salary descending, then name
record Employee(String name, String dept, int salary) implements Comparable<Employee> {
public int compareTo(Employee o) { return name.compareTo(o.name); } // natural order
}
employees.sort(Comparator.comparing(Employee::dept)
.thenComparing(Employee::salary, Comparator.reverseOrder())
.thenComparing(Employee::name));
// nulls last
Comparator.comparing(Employee::dept, Comparator.nullsLast(Comparator.naturalOrder()));Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Find the top 3 highest-paid employees per department with streams and a comparator.
- Explain what goes wrong in a TreeSet whose compareTo returns 0 for unequal objects.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
When do you use Comparable vs Comparator?
Comparable for the one obvious natural order you own (by id, by date). Comparator for alternative orders, for classes you cannot change, or for sorting chosen at runtime.
What does "consistent with equals" mean?
compareTo returns 0 exactly when equals returns true. Sorted sets and maps use compareTo for uniqueness, so if it is inconsistent, a TreeSet can drop elements a HashSet would keep.
Summary
Comparable is one natural order inside the class; Comparator chains give flexible external orders. Use Integer.compare instead of subtraction and keep compareTo consistent with equals.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus