Skip to main content
PreparationZone Logo
PreparationZone
Back to Java

Java · Easy · Free

Comparable vs Comparator — multiple sort orders?

JavaCollectionsFresher
Model answer

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 Comparable when one obvious order exists (IDs, timestamps).
  • Use Comparator.comparing / thenComparing for fluent multi-field sorts.
  • Consistency with equals is 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.