Comparable vs Comparator
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)"Comparable or Comparator?" comes up whenever sorting is discussed. The interviewer is checking that you can pick the right one, chain a multi-field order in one line, and avoid the two classic bugs: subtraction overflow and a TreeSet that loses elements.
Natural order vs external order
Natural order is the default order of a class, written inside the class as compareTo (the Comparable interface). Collections.sort, TreeSet and TreeMap use it when you pass no comparator.
Interviewers ask when you would use each one. The program sorts the same students by roll number (Comparable) and by name (Comparator).
Example 1 · Natural order inside, other orders outside
import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;
class Student implements Comparable<Student> { final int roll; final String name;
Student(int roll, String name) { this.roll = roll; this.name = name; }
@Override public int compareTo(Student other) { return Integer.compare(roll, other.roll); // natural order: by roll }
@Override public String toString() { return roll + ":" + name; }}
public class NaturalOrderDemo { public static void main(String[] args) { List<Student> list = new ArrayList<>(List.of( new Student(3, "Meena"), new Student(1, "Ravi"), new Student(2, "Asha")));
Collections.sort(list); System.out.println("By roll (Comparable): " + list);
list.sort(Comparator.comparing(s -> s.name)); System.out.println("By name (Comparator): " + list);
list.sort(Comparator.reverseOrder()); System.out.println("Roll, reversed: " + list); }}By roll (Comparable): [1:Ravi, 2:Asha, 3:Meena] By name (Comparator): [2:Asha, 3:Meena, 1:Ravi] Roll, reversed: [3:Meena, 2:Asha, 1:Ravi]
What this code does
Collections.sort(list)needs no argument becauseStudentdefines its natural order incompareTo.- The name order lives outside the class, so the class needs no change.
reverseOrder()flips the natural order.
A class that implements Comparable<T> writes int compareTo(T other) inside itself: negative means "I come first", zero means "same position", positive means "I come after". That is the class's natural order, used by Collections.sort(list), TreeSet and TreeMap with no extra argument. String, Integer and LocalDate all have one. Revise: Comparable (opens in a new tab) and Comparator (opens in a new tab).
A Comparator<T> is an outside object with int compare(T a, T b). Use it when you need several orders (by name, by marks, by date) or cannot edit the class.
Comparable: inside the class, one order,compareTo(T o), packagejava.lang.Comparator: outside the class, many orders,compare(T a, T b), packagejava.util.list.sort(null)andCollections.sort(list)use the natural order.- Return any negative / zero / positive int, not just -1, 0, 1.
Predict the output
Predict the comparison
Pick what each line prints.
Round 1 of 3
What does compareTo return for these two names?
Comparator.comparing, thenComparing and reversed
A Comparator is a separate object with a compare(a, b) method that describes one ordering. You can write as many as you need, even for classes you cannot edit.
Build a comparator from keys instead of writing compare by hand. The program orders students by section and roll, then sorts names Z to A and puts nulls last.
Example 2 · Building comparators from keys
import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.List;
record Ticket(String passenger, String coach, int seat) {}
public class ComparingDemo { public static void main(String[] args) { List<Ticket> tickets = new ArrayList<>(List.of( new Ticket("Ravi", "S2", 14), new Ticket("Asha", "S1", 40), new Ticket("John", "S2", 3), new Ticket("Meena", "S1", 7)));
tickets.sort(Comparator.comparing(Ticket::coach).thenComparingInt(Ticket::seat)); tickets.forEach(t -> System.out.println(t.coach() + "-" + t.seat() + " " + t.passenger()));
tickets.sort(Comparator.comparing(Ticket::passenger).reversed()); System.out.println("Names Z to A: " + tickets.stream().map(Ticket::passenger).toList());
List<String> withNull = new ArrayList<>(Arrays.asList("Kiran", null, "Asha")); withNull.sort(Comparator.nullsLast(Comparator.naturalOrder())); System.out.println("Nulls last: " + withNull); }}S1-7 Meena S1-40 Asha S2-3 John S2-14 Ravi Names Z to A: [Ravi, Meena, John, Asha] Nulls last: [Asha, Kiran, null]
What this code does
thenComparingIntbreaks ties within a coach by seat number; seats are compared as numbers, so 7 comes before 40.reversed()flips the name order, andnullsLaststopsnullfrom throwing aNullPointerExceptionwhile sorting.
Comparator.comparing(keyExtractor) builds a comparator from a method reference such as Student::name. thenComparing adds a tie-breaker used only when the earlier keys are equal, and reversed() flips the whole chain built so far.
Use comparingInt, comparingLong or comparingDouble for primitive keys to avoid boxing. Comparator.reverseOrder() reverses natural order, and Comparator.nullsFirst(...) or nullsLast(...) make a comparator null-safe.
Fix the error
Fix the comparator
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Sort employees by salary, highest first.
Error
SortFix.java:8: error: cannot find symbol
list.sort(Comparator.comparing(e -> e.salary()).reversed());
^
symbol: method salary()Comparator.comparing(e -> e.salary()).reversed() does not compile: "cannot find symbol ... location: variable e of type Object". Java cannot infer the type through .reversed(). Use Employee::salary or write (Employee e) -> e.salary().Coding question: salary descending, then name
A tie-breaker is a second key, added with thenComparing, that is used only when the first keys are equal. It makes sure two different objects never compare as equal.
Sorting employees by salary descending, then by name, is asked in almost every Java round. The program shows the one-line answer, and what reversed() does at the end.
Example 3 · Salary descending, then name ascending
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
record Employee(String name, int salary) {}
public class SalarySortDemo { public static void main(String[] args) { List<Employee> staff = new ArrayList<>(List.of( new Employee("Ravi", 60000), new Employee("Asha", 85000), new Employee("Meena", 72000), new Employee("Kiran", 85000), new Employee("Arjun", 60000)));
Comparator<Employee> bySalaryDescThenName = Comparator.comparingInt(Employee::salary).reversed() .thenComparing(Employee::name); staff.sort(bySalaryDescThenName); staff.forEach(e -> System.out.println(e.salary() + " " + e.name()));
staff.sort(Comparator.comparingInt(Employee::salary) .thenComparing(Employee::name).reversed()); System.out.println("reversed() at the end: " + staff.stream().map(Employee::name).toList()); }}85000 Asha 85000 Kiran 72000 Meena 60000 Arjun 60000 Ravi reversed() at the end: [Kiran, Asha, Meena, Ravi, Arjun]
What this code does
reversed()right aftercomparingIntflips only the salary, so ties stay in A to Z name order.- Moving
reversed()to the end flips the name tie-breaker too: Kiran now comes before Asha.
The clean answer is one line: comparingInt(Employee::salary).reversed().thenComparing(Employee::name).
Watch where reversed() goes. Placed after comparingInt, it reverses only the salary part. Placed at the very end, it would also sort names Z to A.
Traps: subtraction overflow and compareTo inconsistent with equals
A comparator is consistent with equals when compare(a, b) is 0 exactly when a.equals(b). TreeSet and TreeMap treat 0 as a duplicate, so an inconsistent comparator makes them drop elements.
Two traps cost marks. The first program shows a subtraction comparator overflowing; the second shows a TreeSet silently dropping employees.
Example 4 · The subtraction comparator overflows
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class OverflowComparatorDemo { public static void main(String[] args) { Comparator<Integer> bad = (a, b) -> a - b; Comparator<Integer> good = Integer::compare;
int low = -2_000_000_000; int high = 1_500_000_000; System.out.println("bad.compare(low, high) = " + bad.compare(low, high)); System.out.println("good.compare(low, high) = " + good.compare(low, high));
List<Integer> balances = new ArrayList<>(List.of(low, high)); balances.sort(bad); System.out.println("Sorted with bad: " + balances); balances.sort(good); System.out.println("Sorted with good: " + balances); }}bad.compare(low, high) = 794967296 good.compare(low, high) = -1 Sorted with bad: [1500000000, -2000000000] Sorted with good: [-2000000000, 1500000000]
What this code does
- -2,000,000,000 minus 1,500,000,000 is -3,500,000,000, which does not fit in an
int, so it wraps round to a positive number. - A positive result claims
lowis bigger, so the bad sort puts it in the wrong place.Integer.comparenever subtracts and is always right.
Example 5 · TreeSet drops employees with equal salaries
import java.util.Comparator;import java.util.List;import java.util.Set;import java.util.TreeSet;
record Employee(String name, int salary) {}
public class TreeSetDropDemo { public static void main(String[] args) { List<Employee> staff = List.of( new Employee("Ravi", 60000), new Employee("Asha", 85000), new Employee("Meena", 72000), new Employee("Kiran", 85000), new Employee("Arjun", 60000));
Set<Employee> bySalary = new TreeSet<>(Comparator.comparingInt(Employee::salary)); bySalary.addAll(staff); System.out.println("Salary only: " + bySalary.size() + " " + bySalary.stream().map(Employee::name).toList());
Set<Employee> total = new TreeSet<>(Comparator.comparingInt(Employee::salary) .thenComparing(Employee::name)); total.addAll(staff); System.out.println("With tie-breaker: " + total.size() + " " + total.stream().map(Employee::name).toList()); }}Salary only: 3 [Ravi, Meena, Asha] With tie-breaker: 5 [Arjun, Ravi, Meena, Asha, Kiran]
What this code does
- The first comparator returns 0 for Asha and Kiran (both 85000), so the TreeSet treats Kiran as a duplicate and drops him. The same happens to Arjun.
- Adding
thenComparing(Employee::name)makes 0 mean "same salary and same name", so no one is lost.
Subtraction comparators such as (a, b) -> a - b look neat but break for large values: int subtraction can overflow and flip the sign, so a very negative number is reported as "bigger". Use Integer.compare(a, b) or comparingInt.
A TreeSet or TreeMap treats a 0 result as a duplicate, so a comparator that looks only at salary silently drops every employee whose salary ties with someone already inside. Always add tie-breakers that make the order total.
Find the bug
Find the comparator bug
Each snippet gives a wrong result. Tap the wrong line, then check the fix.
Sort the balances from lowest to highest.
Round 1 of 3Next step
Check your understanding
12 quick questions