Java · Easy · Free
Comparable vs Comparator — multiple sort orders?
JavaCollectionsFresher
Comparable vs Comparator
Comparable<T> is the natural order inside the type (compareTo). Comparator<T> is an external strategy—multiple sort orders without mutating the class.
- Implement
Comparablewhen one obvious order exists (IDs, timestamps). - Use
Comparator.comparing/thenComparingfor fluent multi-field sorts. - Consistency with
equalsis recommended but not required—document when unequal objects compare equal. - Tim sort exploits existing order in partially sorted data.
java
List<Employee> staff = ...;
staff.sort(Comparator.comparing(Employee::dept)
.thenComparing(Employee::salary, Comparator.reverseOrder()));Mention
Comparator.nullsFirst—production sorts need explicit null policy.