Sorting and comparators
What you will learn
Sorting arranges values according to an ordering rule. Natural order comes from Comparable; a Comparator supplies an alternative order, such as ranking deliveries by priority and then by tracking code. Choose the rule explicitly before sorting or searching.
- Use natural and custom ordering to sort arrays and lists.
- Compose comparators with explicit tie-breaking and null handling.
- Explain stability and avoid subtraction overflow.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed.
Sort numbers without changing the source
import java.util.*;public class Main {
public static void main(String[] args) { List<Integer> source = List.of(8, 2, 5, 2); List<Integer> sorted = new ArrayList<>(source); sorted.sort(null); System.out.println(source); System.out.println(sorted); int[] a = {9, 1, 4}; Arrays.sort(a); System.out.println(Arrays.toString(a)); }}Expected output:
[8, 2, 5, 2][2, 2, 5, 8][1, 4, 9]The copy is mutable and preserves the original list; sorting retains duplicate values.
Rules and mental model
list.sort(null) sorts by natural order; list.sort(comparator) uses an explicit comparator. Collections.sort provides equivalent list sorting overloads. They require a modifiable list, not necessarily a resizable one. Arrays.sort sorts arrays in place, with comparator overloads for reference arrays, not primitive arrays. Sorting a list or object array is stable: equal-ranked items retain their relative input order. Stability does not sort ties by a secondary field unless you supply that rule. A comparator should return a negative value, zero or positive value, with consistent signs, transitive ordering and consistent behavior for ties. Never subtract arbitrary int keys to compare them: the result may overflow. Integer.compare(a,b) handles extreme values.
Comparator.comparingInt extracts an int key. thenComparing adds a tie-breaker; reversed flips the comparator it is applied to. Comparator.nullsLast and nullsFirst wrap a comparator when null values must be placed explicitly. The syntax Job::code denotes a reference to the record accessor; it is shorthand for job -> job.code(). This is a preview of the next chapter’s method references, not a prerequisite for understanding the ordering rule. When comparing map keys, zero means equivalent keys for TreeMap regardless of equals; when sorting a list, equal-ranked items both remain. For sorting copies, construct a mutable ArrayList first to avoid changing the source. Avoid relying on implementation-specific sort algorithms or treating stability as a universal property of every sort.
Rank jobs with a tie-breaker
import java.util.*;public class Main { record Job(String code, int priority) {} public static void main(String[] args) { List<Job> jobs = new ArrayList<>(List.of(new Job("C", 2), new Job("B", 5), new Job("A", 5))); Comparator<Job> order = Comparator.comparingInt(Job::priority).reversed().thenComparing(Job::code); jobs.sort(order); for (Job j : jobs) System.out.println(j.code()); }}Expected output:
ABCHigher priority comes first; equal priority is resolved by ascending code. Reversed applies before the tie-breaker.
See stability and explicit null placement
import java.util.*;public class Main { record Job(String code, int priority) {} public static void main(String[] args) { List<Job> jobs = new ArrayList<>(List.of(new Job("B", 1), new Job("A", 1), new Job("C", 0))); jobs.sort(Comparator.comparingInt(Job::priority)); for (Job job : jobs) System.out.println(job.code()); List<String> names = new ArrayList<>(Arrays.asList("Z", null, "A")); names.sort(Comparator.nullsLast(Comparator.naturalOrder())); System.out.println(names); }}Expected output:
CBA[A, Z, null]B remains ahead of A because their priority ties and the sort is stable. The names comparator explicitly places null last.
Common mistakes
Avoid return a.priority() - b.priority(); because signed overflow may reverse the comparison. Also primary.thenComparing(secondary).reversed() reverses both rules, whereas primary.reversed().thenComparing(secondary) reverses only the primary rule.
Practice
Sort jobs X(priority 1), B(priority 3), A(priority 3) by descending priority and ascending code. Print each code. Use a mutable copy and a composed comparator.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sorting and comparators — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
Two jobs compare equal by priority. A stable list sort does what?
Which comparison is safe for arbitrary int values?
How do you sort by descending priority then ascending code?
What does sorting List.of(3,1) directly require that it lacks?
What is the effect of comparator equality in a TreeMap?