Java Sorting: Comparable, Comparator, Collections.sort and binarySearch (OCP 21)
Sorting for the OCP 21 exam: writing compareTo with Comparable, building Comparator objects with lambdas, comparing, thenComparing and reversed, Collections.sort versus List.sort, binarySearch return values, and why TreeSet fails at run time without an order.
kvi5hnuCode Sprout team member9 min readOn this page
Sorting needs an answer to one question: given two objects, which comes first? Java has two interfaces for answering it.
Comparable<T>: the class itself defines its natural order, for example by name.Comparator<T>: a separate object defines an order, and you can have as many as you like.
String, the wrapper classes (Integer, Double and so on), BigDecimal, BigInteger, LocalDate and StringBuilder all implement Comparable. Numbers sort numerically. Strings sort by Unicode value, so digits come before uppercase letters, which come before lowercase letters.

The return value contract
Both compareTo(other) and compare(a, b) return an int whose sign is all that matters:
| Result | Meaning |
|---|---|
| negative | the first object (this, or a) comes before the other |
| zero | they're equal for sorting purposes |
| positive | the first object comes after the other |
The exact number isn't specified: "apple".compareTo("apricot") happens to be -2, the difference between 'p' and 'r'. Exam answers that depend on it come from String.compareTo or a subtraction in the code shown. A tip for reading them: in a.compareTo(b), ask "is a smaller?" If yes, the result is negative.
Implementing Comparable
public record Planet(String name, double massKg) implements Comparable<Planet> {
public int compareTo(Planet other) {
return name.compareTo(other.name); // natural order: by name
}
}
List<Planet> sky = new ArrayList<>(List.of(new Planet("Mars", 6.4e23), new Planet("Earth", 6.0e24)));
Collections.sort(sky); // [Planet[name=Earth, ...], Planet[name=Mars, ...]]
Rules to check in exam code:
Comparableis generic, and its only method isint compareTo(T o). ImplementingComparable<Planet>means the parameter is aPlanet, so no cast is needed.- The method is
public, because interface methods are public. Leaving outpublicdoesn't compile. - Writing
compareTo(Object o)while implementingComparable<Planet>doesn't compile: it doesn't override the interface method. With the raw typeimplements Comparable, the parameter isObject, and you cast (or pattern-match withinstanceof) yourself. That compiles (javac flags the raw type only with-Xlint:rawtypes, but IDEs warn about it). - Both classes and records can implement
Comparable.
For numbers, you'll see two ways to compare:
return Integer.compare(this.size, other.size); // safe
return this.size - other.size; // common on the exam, ascending order
return other.size - this.size; // descending order
Subtraction is fine for small values, but it can overflow: Integer.MIN_VALUE - 1 wraps around to a large positive number, which gives the wrong sign. Real code should use Integer.compare, Long.compare or Double.compare. The exam still uses subtraction, so read it as "ascending if this comes first".
Writing a Comparator
Comparator<T> is a functional interface whose abstract method is int compare(T a, T b). It also declares equals, but that doesn't count, because Object already provides it (article 47). Three ways to write the same comparator:
Comparator<Planet> byMass1 = new Comparator<>() { // anonymous class
public int compare(Planet a, Planet b) {
return Double.compare(a.massKg(), b.massKg());
}
};
Comparator<Planet> byMass2 = (a, b) -> Double.compare(a.massKg(), b.massKg()); // lambda
Comparator<Planet> byMass3 = Comparator.comparingDouble(Planet::massKg); // helper method
A classic trap is an anonymous Comparator that declares compareTo(a, b) instead of compare(a, b). It doesn't compile.
Comparable is technically a functional interface too, but writing it as a lambda makes little sense, because its point is to live inside the class.
Helper methods
Static methods on Comparator create a comparator:
| Static method | Compares by |
|---|---|
comparing(keyExtractor) | a Comparable key such as a String (primitives are boxed) |
comparing(keyExtractor, keyComparator) | a key, using the given comparator for the key |
comparingInt / comparingLong / comparingDouble | a primitive key, without boxing |
naturalOrder() / reverseOrder() | the objects' own compareTo, ascending or descending |
nullsFirst(cmp) / nullsLast(cmp) | cmp, putting null elements first or last |
Default methods chain onto an existing comparator:
| Default method | Effect |
|---|---|
thenComparing(keyExtractor) (or (comparator)) | breaks ties of the previous comparator |
thenComparingInt / Long / Double | breaks ties using a primitive key |
reversed() | reverses the whole comparator built so far |
record Runner(String team, String name, int seconds) {}
Comparator<Runner> c1 = Comparator.comparing(Runner::team)
.thenComparingInt(Runner::seconds); // team A-Z, then fastest
Comparator<Runner> c2 = Comparator.comparing(Runner::team)
.thenComparingInt(Runner::seconds)
.reversed(); // team Z-A, then slowest
Comparator<Runner> c3 = Comparator.comparing(Runner::team).reversed()
.thenComparingInt(Runner::seconds); // team Z-A, then fastest
Comparator<Runner> c4 = Comparator.comparing(Runner::seconds, Comparator.reverseOrder()); // slowest first
The position of reversed() matters. It flips everything before it in the chain, and nothing after it.
Type mistakes the exam checks for:
Comparator.comparingInt(Runner::name)doesn't compile, becausenameisn't anint.thenComparingis a default (instance) method, soComparator.thenComparing(...)called on the interface doesn't compile.- Inference stops at the first call in a chain.
Comparator.comparing(s -> s.length()).reversed()doesn't compile, becausesis inferred asObjectbeforereversed()is applied. Fix it with a method reference (String::length) or an explicit type ((String s) -> s.length()). Without.reversed(), the same lambda compiles. Comparator.naturalOrder().reversed()assigned toComparator<Planet>fails for the same reason. WriteComparator.<Planet>naturalOrder().reversed(), or simplyComparator.reverseOrder().
Sorting
| Call | Order used |
|---|---|
Collections.sort(list) | natural order. The element type must be Comparable, checked at compile time |
Collections.sort(list, comparator) | the comparator |
list.sort(comparator) | the comparator. list.sort(null) means natural order (checked only at run time) |
Arrays.sort(array) / Arrays.sort(array, comparator) | the same, for arrays |
Collections.sort returns void, so Collections.sort(list).reverse() doesn't compile. Use Collections.reverse(list) as a separate step, or sort with a reversed comparator.
record Badge(int number) {} // NOT Comparable
List<Badge> badges = new ArrayList<>(List.of(new Badge(3), new Badge(1)));
Collections.sort(badges); // DOES NOT COMPILE
Collections.sort(badges, (a, b) -> a.number() - b.number()); // fine: [Badge[number=1], Badge[number=3]]
badges.sort(Comparator.comparingInt(Badge::number).reversed()); // fine: [Badge[number=3], Badge[number=1]]
The sorts for objects (Collections.sort, List.sort, Arrays.sort on object arrays) are stable: elements that compare equal keep their original relative order. Sorting a null element under natural order throws NullPointerException. Wrap the comparator with nullsFirst or nullsLast to allow nulls.
Sorted collections check at run time
TreeSet and TreeMap need an order, but the compiler doesn't enforce it. new TreeSet<Badge>() compiles. The first add throws a ClassCastException ("cannot be cast to class java.lang.Comparable"), even when the set is empty, because the element is compared with itself.
The fix is to pass a Comparator to the constructor:
Set<Badge> ok = new TreeSet<>(Comparator.comparingInt(Badge::number));
ok.add(new Badge(9)); // fine
The same applies to TreeMap keys, and also to list.sort(null) and Arrays.sort on objects that aren't Comparable. These all compile. TreeSet/TreeMap fail on the first insertion, while the sorts throw ClassCastException as soon as two elements are compared, so an empty or single-element list sorts without error.
Binary search
Collections.binarySearch(list, key) and Arrays.binarySearch(array, key) find a key in a sorted list or array quickly:
- If the key is found, they return its index.
- If not, they return
-(insertionPoint) - 1, where the insertion point is the index where the key would go. That's always negative, even when the key would be inserted at index 0.
List<Integer> years = new ArrayList<>(List.of(2021, 1999, 2010, 2005));
Collections.sort(years); // [1999, 2005, 2010, 2021]
Collections.binarySearch(years, 2010); // 2
Collections.binarySearch(years, 2000); // would go at index 1: -1 - 1 = -2
Collections.binarySearch(years, 1900); // index 0: -1
Collections.binarySearch(years, 2030); // index 4: -5
The list must be sorted in the same order that the search uses:
- After sorting with a comparator, pass the same comparator:
binarySearch(list, key, comparator). - Searching an unsorted list, or one sorted differently, gives an undefined result. On the exam, "the result is undefined" is the right answer, whatever number the program happens to print.
Collections.binarySearch(list, key)without a comparator needsComparableelements. Otherwise it doesn't compile, just likeCollections.sort.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
List.sort(comparator)(Java 8) is the modern alternative toCollections.sort(list, comparator). Both give the same stable sort.
Exam traps from this article
A complete example
The program sorts a shelf of Book records by their natural order, by a hand-written comparator and by chained comparators, showing exactly where reversed() takes effect. It then searches with binarySearch, shows TreeSet failing without an order and working with a comparator, handles null, and demonstrates the overflow in subtraction comparators.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Solution {
// Natural order: by title
record Book(String title, int year, int pages) implements Comparable<Book> {
public int compareTo(Book other) {
return title.compareTo(other.title);
}
@Override
public String toString() {
return title + "(" + year + "," + pages + ")";
}
}
// Not Comparable at all
record Ticket(int seat) {}
public static void main(String[] args) {
List<Book> shelf = new ArrayList<>(List.of(
new Book("Rivers", 2019, 310),
new Book("Atlas", 2021, 120),
new Book("Maple", 2019, 450),
new Book("Comet", 2021, 120)));
// 1. Natural order (compareTo)
Collections.sort(shelf);
System.out.println("by title: " + shelf);
// 2. A Comparator written by hand, then built from helper methods
Comparator<Book> byPagesManual = (a, b) -> Integer.compare(a.pages(), b.pages());
shelf.sort(byPagesManual);
System.out.println("by pages: " + shelf);
Comparator<Book> byYearThenPages = Comparator.comparingInt(Book::year)
.thenComparingInt(Book::pages);
shelf.sort(byYearThenPages);
System.out.println("year, pages: " + shelf);
// 3. reversed() applies to everything chained before it
shelf.sort(Comparator.comparingInt(Book::year).thenComparing(Book::title).reversed());
System.out.println("all reversed: " + shelf);
shelf.sort(Comparator.comparingInt(Book::year).reversed().thenComparing(Book::title));
System.out.println("year desc only: " + shelf);
// 4. compareTo results are only signs, not fixed values
System.out.println("\"Atlas\" vs \"Comet\": " + "Atlas".compareTo("Comet")
+ ", 7 vs 3: " + Integer.compare(7, 3));
// 5. Binary search needs a list sorted the same way
List<Integer> years = new ArrayList<>(List.of(2021, 1999, 2010, 2005));
Collections.sort(years);
System.out.println("years " + years + ": find 2010 -> " + Collections.binarySearch(years, 2010)
+ ", find 2000 -> " + Collections.binarySearch(years, 2000));
years.sort(Comparator.reverseOrder());
System.out.println("descending " + years + ": find 2000 with same comparator -> "
+ Collections.binarySearch(years, 2000, Comparator.reverseOrder()));
// 6. Sorted collections check Comparable only at run time
try {
Set<Ticket> broken = new TreeSet<>();
broken.add(new Ticket(4));
} catch (ClassCastException e) {
System.out.println("TreeSet without Comparable: ClassCastException");
}
Set<Ticket> seats = new TreeSet<>(Comparator.comparingInt(Ticket::seat).reversed());
seats.add(new Ticket(4));
seats.add(new Ticket(11));
seats.add(new Ticket(7));
System.out.println("TreeSet with Comparator: " + seats);
// 7. Arrays and null handling
String[] words = {"pear", "Fig", "apple", null};
Arrays.sort(words, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER));
System.out.println("arrays + nullsLast: " + Arrays.toString(words));
// 8. Why subtraction comparators are risky
Comparator<Integer> subtract = (a, b) -> a - b;
System.out.println("MIN_VALUE vs 1 by subtraction: " + subtract.compare(Integer.MIN_VALUE, 1)
+ " (wrong sign), by Integer.compare: " + Integer.compare(Integer.MIN_VALUE, 1));
}
}
Output:
by title: [Atlas(2021,120), Comet(2021,120), Maple(2019,450), Rivers(2019,310)]
by pages: [Atlas(2021,120), Comet(2021,120), Rivers(2019,310), Maple(2019,450)]
year, pages: [Rivers(2019,310), Maple(2019,450), Atlas(2021,120), Comet(2021,120)]
all reversed: [Comet(2021,120), Atlas(2021,120), Rivers(2019,310), Maple(2019,450)]
year desc only: [Atlas(2021,120), Comet(2021,120), Maple(2019,450), Rivers(2019,310)]
"Atlas" vs "Comet": -2, 7 vs 3: 1
years [1999, 2005, 2010, 2021]: find 2010 -> 2, find 2000 -> -2
descending [2021, 2010, 2005, 1999]: find 2000 with same comparator -> -4
TreeSet without Comparable: ClassCastException
TreeSet with Comparator: [Ticket[seat=11], Ticket[seat=7], Ticket[seat=4]]
arrays + nullsLast: [apple, Fig, pear, null]
MIN_VALUE vs 1 by subtraction: 2147483647 (wrong sign), by Integer.compare: -1
Points to notice:
- The
Bookrecord'scompareTodefines the natural order by title, used byCollections.sort(shelf). AtlasandCometboth have 120 pages, and their order didn't change in the "by pages" sort: the sort is stable.- "all reversed" puts both year and title in descending order. "year desc only" reverses just the year, because
reversed()comes beforethenComparing. - 2000 isn't in the ascending list. It would go at index 1, so the result is
-2. In the descending list it would go at index 3, giving-4, but only because the search used the same comparator as the sort. - The subtraction comparator returned a positive value for
MIN_VALUEvs1, which is wrong.
Common questions
Should a class implement Comparable at all?
Only when there's one obvious natural order, such as numbers, dates or a name. For anything else, keep the class plain and use comparators where you sort.
What's the difference between Collections.sort(list, c) and list.sort(c)?
None in behavior: Collections.sort simply calls list.sort. list.sort is the modern form, added in Java 8.
Does reverseOrder() equal naturalOrder().reversed()?
They produce the same order. Collections.reverseOrder() is the older equivalent, and it also has an overload that reverses a given comparator.
Is binarySearch faster than indexOf?
On a sorted ArrayList or array, yes: it takes about log₂(n) steps instead of n. On a LinkedList, the advantage mostly disappears, because there's no fast index access.
Summary
Comparable.compareTo(T)defines the natural order inside the class.Comparator.compare(T, T)defines any order outside it.- Return values: negative means before, zero means equal, positive means after. Prefer
Integer.compareto subtraction. - Build comparators with
comparing,comparingInt,thenComparing,reversed,naturalOrder,reverseOrder,nullsFirstandnullsLast. Collections.sortchecksComparableat compile time.TreeSet,TreeMapandlist.sort(null)check it at run time.binarySearchreturns the index, or-(insertion point) - 1, but only on data sorted the same way.
Practice quiz
Test yourself with the sorting quiz: 10 exam-style questions with explanations.
Previous: Java Map Interface: HashMap, TreeMap and Methods like merge and compute (OCP 21)
Next: Java Sequenced Collections: SequencedCollection, SequencedSet and SequencedMap (OCP 21)
Related reading
- Java Map Interface: HashMap, TreeMap and Methods like merge and compute (OCP 21)
- Java Set, Queue and Deque: HashSet, TreeSet, ArrayDeque and Their Methods (OCP 21)
- Java List Interface: ArrayList, LinkedList, Factory Methods and List Operations (OCP 21)
- Java Collections Framework: The Collection Interface and Common Methods (OCP 21)
- Java Variable Scope and Garbage Collection (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.