Lesson 8 of 12 · 8 min · Collections, streams and generics

Sorting with Comparable and Comparator

Covers: Java 25 LTS (also valid on 21). Updated 13 Nov 2026. Part of the Java Full Stack Developer roadmap.

What you will learn

  • Natural ordering with Comparable
  • Custom ordering with Comparator, and its modern factory methods
  • Sort lists, arrays and streams
  • How TreeSet and TreeMap use ordering
  • The comparison contract, and common bugs such as overflow

In simple words

Sorting needs a rule for "which comes first". For numbers and words Java already knows the rule. For your own objects, like students, you must teach it: by marks, by name, or by joining date. Comparable is the object saying "this is my natural order". A Comparator is a separate judge you bring in when you want a different order for the same objects.

Words to know

  • Natural ordering: the default order for a type, such as alphabetical for strings.
  • Comparator: a separate object that defines an order between two items.
  • Stable sort: a sort that keeps equal items in their original relative order.
  • Tie-breaker: a second rule used when the first rule says two items are equal.

Comparable: the natural order

A class implements Comparable<T> and provides compareTo:

public record Student(String name, int marks) implements Comparable<Student> {
    @Override
    public int compareTo(Student other) {
        return Integer.compare(this.marks, other.marks);   // ascending by marks
    }
}

compareTo returns a negative number if this object comes first, zero if they are equal in order, and positive if it comes after. Then:

List<Student> list = new ArrayList<>(List.of(
    new Student("Asha", 82), new Student("Ravi", 67), new Student("Meena", 91)));
Collections.sort(list);        // or list.sort(null)
// Ravi 67, Asha 82, Meena 91

String, Integer, LocalDate and enums are already Comparable. A class can have only one natural order, so use Comparable when there is one obvious order.

Comparator: any order you like

A Comparator<T> has one method, compare(a, b), with the same negative, zero, positive meaning. Pass it to sort:

list.sort(new Comparator<Student>() {                       // old style
    public int compare(Student a, Student b) { return a.name().compareTo(b.name()); }
});

list.sort((a, b) -> a.name().compareTo(b.name()));          // lambda

Modern code uses the factory methods, which are shorter and safer:

list.sort(Comparator.comparing(Student::name));                         // by name
list.sort(Comparator.comparingInt(Student::marks));                     // by marks (avoids boxing)
list.sort(Comparator.comparingInt(Student::marks).reversed());          // highest first
list.sort(Comparator.comparing(Student::marks, Comparator.reverseOrder()));

list.sort(Comparator.comparingInt(Student::marks).reversed()            // marks high to low,
          .thenComparing(Student::name));                               // then name A to Z

thenComparing is the tie-breaker. Always add one when the first key can repeat, so the order is fully defined.

Handle null values explicitly:

Comparator.comparing(Student::name, Comparator.nullsLast(String::compareTo))

Comparator.naturalOrder() and reverseOrder() use the natural ordering. Sorting is stable for objects (List.sort, Collections.sort, Arrays.sort(T[], ...), Stream.sorted()), so equal elements keep their original order, which makes multi-step sorts work (sort by name first, then by marks).

Sorting different things

Arrays.sort(numbers);                               // int[]: ascending
Arrays.sort(students, Comparator.comparing(Student::name));   // Student[]
Collections.sort(list);                             // List with natural order
Collections.reverse(list);                          // reverse the current order
Collections.max(list), Collections.min(list)        // by natural order
Collections.max(list, comparator)

students.stream().sorted(Comparator.comparingInt(Student::marks).reversed()).limit(3).toList();   // top 3

For primitive arrays (int[]), Arrays.sort uses a dual-pivot quicksort and is not stable (it does not matter for primitives). For objects, it uses TimSort, which is stable.

TreeSet and TreeMap

Sorted collections keep elements in order using Comparable or a Comparator given to the constructor:

Set<Student> byMarks = new TreeSet<>();                                // uses compareTo
Set<Student> byName  = new TreeSet<>(Comparator.comparing(Student::name));

Important: a TreeSet or TreeMap uses the comparison, not equals, to decide whether two elements are the same. If your comparator says two different students are equal (the same marks), the set treats them as duplicates and keeps only one. Include enough fields (a tie-breaker such as the id) to make the order consistent with equals:

Comparator.comparingInt(Student::marks).thenComparing(Student::name)

TreeMap offers firstKey(), lastKey(), floorKey(), ceilingKey(), headMap(), tailMap() and subMap(), useful for ranges (for example the nearest price tier).

The contract

A comparison must be consistent:

  • Antisymmetric: the sign of compare(a, b) is the opposite of compare(b, a).
  • Transitive: if a > b and b > c, then a > c.
  • Consistent with equals (strongly recommended): compare(a, b) == 0 should mean a.equals(b); otherwise sorted sets and maps behave surprisingly.

Violating it can produce "Comparison method violates its general contract!" at run time or silently wrong order.

Common bugs

  • Subtraction overflow: return a.marks - b.marks; can overflow for large or negative values and give the wrong sign. Use Integer.compare(a, b) or Comparator.comparingInt.
  • Comparing doubles with == or subtraction: use Double.compare.
  • Forgetting the tie-breaker, so equal items appear in unpredictable relative order, or vanish from a TreeSet.
  • NullPointerException when sorting a list that contains null or a null field; use nullsFirst or nullsLast.
  • Making a class Comparable for one particular use when a Comparator is the better choice.
  • Mutating an element's sort field while it is inside a TreeSet or TreeMap, which corrupts the order.

Choosing between them

Comparable Comparator
Where the rule lives inside the class outside, in any place
How many orders one (natural) as many as you like
Can you change a class you do not own? no yes
Typical use dates, numbers, ids, versions sort by name, then marks, in one report

Common mistakes (summary)

  • Using subtraction in compareTo.
  • Skipping tie-breakers.
  • Ignoring nulls.
  • Treating TreeSet like a HashSet and losing "duplicate" elements.

Try it yourself

  1. Sort a list of students by marks descending, then by name ascending.
  2. Write a Comparable Version class ("1.10.0" must come after "1.9.3").
  3. Put students with equal marks into a TreeSet using only marks, and see what happens; then add a tie-breaker.
  4. Find the top three scorers with a stream.
  5. Show an overflow bug using subtraction with Integer.MIN_VALUE.

Check yourself

What is the difference between Comparable and Comparator?

Comparable defines a class's natural order inside the class (compareTo); a Comparator is a separate object defining an order (compare), so there can be many.

What does compareTo return?

A negative number if this object is smaller, zero if equal in order, positive if larger.

Why is return a - b risky in compare?

Integer subtraction can overflow and give the wrong sign; use Integer.compare(a, b).

Why can a TreeSet drop elements that are not equals?

It uses the comparison to detect duplicates, so elements the comparator considers equal are treated as the same and only one is kept.

Interview questions

How do you sort a list of objects by two fields?

list.sort(Comparator.comparing(A::first).thenComparing(A::second)), adding .reversed() or Comparator.reverseOrder() where needed.

How does TreeMap decide whether two keys are equal?

By the comparison (compareTo or the comparator returning zero), not by equals, so the ordering must be consistent with equality.

Which sorting algorithm does Collections.sort use, and is it stable?

TimSort for objects, a hybrid merge and insertion sort. It is stable and O(n log n) in the worst case.

Summary

  • Comparable gives one natural order; Comparator provides any number of orders.
  • Use Comparator.comparing, thenComparing, reversed and nullsLast instead of hand-written subtraction.
  • Sorted sets and maps use the comparison, so add tie-breakers consistent with equals.
  • Object sorts are stable (TimSort); avoid overflow and null pitfalls.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.