Skip to content

Module 9 · Collections and Generics — topic 5 of 5

Comparable, Comparator and Sorting

Natural ordering with Comparable, custom orderings with Comparator, comparing/thenComparing/reversed chains, stable sorting, and sorted collections.

Beginner 15 min read·Lesson 34 of 39 in Java Programming

Learning objectives

  • Implement Comparable for natural ordering
  • Build Comparators with comparing, thenComparing and reversed
  • Sort lists and use comparators with TreeMap, TreeSet and PriorityQueue

Definition

Comparable defines a class's natural ordering through compareTo. A Comparator is a separate object defining an ordering through compare, allowing many different orderings for the same class. Both return a negative number, zero or a positive number.

Introduction

Sorting numbers and strings works out of the box, but how should a list of students be sorted — by marks, by name, by roll number? Java separates the sorting algorithm from the ordering: you supply the ordering, and List.sort or Collections.sort does the rest.

Why it matters

Leaderboards, reports, search results and schedules all need custom sort orders.

TreeMap, TreeSet and PriorityQueue are driven by the same comparison rules.

Detailed explanation

The contract. compare(a, b) (or a.compareTo(b)) returns a negative number if a comes first, zero if they are equal in that ordering, and a positive number if b comes first. Use Integer.compare(x, y) rather than x - y, which can overflow.

Comparable — implement Comparable<Student> and compareTo to give a class a *natural ordering* (String: alphabetical, Integer: numeric, LocalDate: chronological). There can be only one natural ordering.

Comparator — any number of external orderings. Since Java 8 you rarely write the method yourself: Comparator.comparing(Student::marks), then .reversed(), .thenComparing(Student::name), Comparator.comparingInt, Comparator.naturalOrder(), Comparator.nullsLast(...).

Sorting. list.sort(cmp) or Collections.sort(list) (natural order). For arrays: Arrays.sort(arr) and Arrays.sort(objs, cmp). Java's object sort (TimSort) is stable: elements that compare equal keep their original relative order, which is what makes multi-key sorting by successive sorts possible.

Sorted collections. new TreeSet<>(cmp), new TreeMap<>(cmp) and new PriorityQueue<>(cmp) use the comparator to order elements. Careful: a TreeSet treats elements that compare as 0 as *duplicates*, even if equals says they differ.

Consistency. Ideally compareTo is consistent with equals (returns 0 exactly when equals is true); otherwise sorted and hashed collections may disagree about duplicates.

Syntax

Java
class Student implements Comparable<Student> {
public int compareTo(Student o) { return Integer.compare(roll, o.roll); }
}
students.sort(Comparator.comparing(Student::marks).reversed()
.thenComparing(Student::name));
PriorityQueue<Task> pq = new PriorityQueue<>(Comparator.comparingInt(Task::priority));
  • Never use subtraction in compare for ints that may overflow.
  • Comparators compose: reversed, thenComparing, nullsFirst.
  • TreeSet uses compare (not equals) to detect duplicates.

Code examples

Natural ordering with Comparable

Java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Version> versions = new ArrayList<>(List.of(new Version(1, 10), new Version(1, 2), new Version(2, 0), new Version(1, 9)));
Collections.sort(versions);
System.out.println(versions);
System.out.println("max: " + Collections.max(versions));
List<String> words = new ArrayList<>(List.of("banana", "Apple", "cherry"));
Collections.sort(words);
System.out.println(words + " (uppercase sorts first)");
words.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(words);
}
}
record Version(int major, int minor) implements Comparable<Version> {
@Override public int compareTo(Version o) {
int c = Integer.compare(major, o.major);
return c != 0 ? c : Integer.compare(minor, o.minor);
}
@Override public String toString() { return major + "." + minor; }
}
Output
[1.2, 1.9, 1.10, 2.0]
max: 2.0
[Apple, banana, cherry] (uppercase sorts first)
[Apple, banana, cherry]

Comparator chains

Java
import java.util.*;
public class Main {
record Student(String name, String branch, int marks) { }
public static void main(String[] args) {
List<Student> list = new ArrayList<>(List.of(
new Student("Ravi", "ECE", 82), new Student("Asha", "CSE", 91),
new Student("Meera", "CSE", 82), new Student("John", "ECE", 91)));
list.sort(Comparator.comparingInt(Student::marks).reversed().thenComparing(Student::name));
list.forEach(s -> System.out.println(s.marks() + " " + s.name()));
list.sort(Comparator.comparing(Student::branch).thenComparing(Student::marks, Comparator.reverseOrder()));
System.out.println(list.stream().map(s -> s.branch() + ":" + s.name()).toList());
}
}
Output
91 Asha
91 John
82 Meera
82 Ravi
[CSE:Asha, CSE:Meera, ECE:John, ECE:Ravi]

More examples

Leaderboards, stable sorting and the TreeSet trap

Java
import java.util.*;
public class Main {
record Player(String name, int score, int joined) { }
public static void main(String[] args) {
List<Player> players = new ArrayList<>(List.of(
new Player("Zara", 300, 3), new Player("Arun", 450, 1), new Player("Bala", 300, 2), new Player("Chen", 450, 4)));
List<Player> stable = new ArrayList<>(players);
stable.sort(Comparator.comparingInt(Player::score).reversed()); // ties keep list order
System.out.println("stable: " + names(stable));
Comparator<Player> ranking = Comparator.comparingInt(Player::score).reversed().thenComparingInt(Player::joined);
players.sort(ranking);
for (int i = 0; i < players.size(); i++) System.out.println((i + 1) + ". " + players.get(i).name() + " " + players.get(i).score());
Set<Player> byScoreOnly = new TreeSet<>(Comparator.comparingInt(Player::score));
byScoreOnly.addAll(players);
System.out.println("TreeSet by score keeps " + byScoreOnly.size() + " of 4: " + names(new ArrayList<>(byScoreOnly)));
PriorityQueue<Player> next = new PriorityQueue<>(Comparator.comparingInt(Player::joined));
next.addAll(players);
System.out.println("earliest joiner: " + next.peek().name());
System.out.println("overflow-safe compare: " + Integer.compare(Integer.MIN_VALUE, 1) + " vs subtraction: " + (Integer.MIN_VALUE - 1));
}
static List<String> names(List<Player> ps) { return ps.stream().map(Player::name).toList(); }
}
Output
stable: [Arun, Chen, Zara, Bala]
1. Arun 450
2. Chen 450
3. Bala 300
4. Zara 300
TreeSet by score keeps 2 of 4: [Bala, Arun]
earliest joiner: Arun
overflow-safe compare: -1 vs subtraction: 2147483647

Step-by-step explanation

  • Sorting by score only is stable: Arun stays before Chen and Zara before Bala, as in the original list.
  • The ranking comparator breaks ties by join order, so the result no longer depends on the input order.
  • A TreeSet ordered only by score treats players with equal scores as duplicates, keeping just one per score — a common bug.
  • A PriorityQueue with a comparator always exposes the smallest element according to it, here the earliest joiner.
  • Integer.MIN_VALUE - 1 overflows to a large positive number, which would make a subtraction-based comparator give the wrong answer; Integer.compare is always correct.

Expected output

Running “Leaderboards, stable sorting and the TreeSet trap” prints exactly:

TextOutput
stable: [Arun, Chen, Zara, Bala]
1. Arun 450
2. Chen 450
3. Bala 300
4. Zara 300
TreeSet by score keeps 2 of 4: [Bala, Arun]
earliest joiner: Arun
overflow-safe compare: -1 vs subtraction: 2147483647

Practical applications

  • Leaderboards and rankings
  • Sorting tables by clicked column in admin panels
  • Scheduling with priority queues
  • Ordering dates, versions and prices

Best practices

  • Build comparators with comparing/thenComparing instead of writing compare by hand.
  • Always add a deterministic tie-breaker for rankings.
  • Implement Comparable only for a single, obvious natural ordering.

Common mistakes

Subtraction in compare

Avoid

(a, b) -> a.balance - b.balance

Prefer

Comparator.comparingInt(Account::balance)

Subtraction overflows for large positive and negative values and returns the wrong sign.

A TreeSet with an incomplete comparator

Avoid

new TreeSet<>(Comparator.comparing(Student::marks))

Prefer

new TreeSet<>(Comparator.comparing(Student::marks).thenComparing(Student::roll))

Elements that compare as 0 are considered duplicates and silently dropped; add tie-breakers that make every element unique.

Important notes

  • Collections.sort(list) and list.sort(null) both use natural ordering and throw ClassCastException if elements aren't Comparable.
  • Arrays.sort on primitive arrays isn't stable — but stability doesn't matter for primitives.

Key takeaways

  • compare/compareTo return negative, zero or positive.
  • Comparable = one natural order; Comparator = any number of orders, composable with thenComparing and reversed.
  • Java's object sort is stable; sorted collections drop elements that compare equal.

Try it yourself

  1. 1
    Sort a list of files by extension, then by size descending, then by name.
  2. 2
    Implement Comparable for a Money record and use it to find the most expensive item.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • ModerateWhat is printed?
  • AdvancedWhat is printed?
Practise this topic