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.
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
- 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
[1.2, 1.9, 1.10, 2.0] max: 2.0 [Apple, banana, cherry] (uppercase sorts first) [Apple, banana, cherry]
Comparator chains
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
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
rankingcomparator 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 - 1overflows to a large positive number, which would make a subtraction-based comparator give the wrong answer;Integer.compareis always correct.
Expected output
Running “Leaderboards, stable sorting and the TreeSet trap” prints exactly:
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
Prefer
Subtraction overflows for large positive and negative values and returns the wrong sign.
A TreeSet with an incomplete comparator
Avoid
Prefer
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
- 1Sort a list of files by extension, then by size descending, then by name.
- 2Implement Comparable for a
Moneyrecord 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?