Passing Comparators to Sort Methods
You'll learn how to supply custom Comparator instances to Java's sorting utilities to control sort order without modifying your classes.
The Core Idea
Now that you can create Comparator instances (including using naturalOrder() and reverseOrder()), it's time to use them. Java's sorting methods accept a Comparator as an optional parameter, letting you define sort order at the call site rather than being locked into natural ordering.
Think of it like giving directions to a delivery driver: instead of always following the default route (natural ordering), you hand them a custom map (your Comparator) that tells them exactly how to prioritize stops.
Key Sorting Methods That Accept Comparators
Collections.sort(List, Comparator)
Sorts a List in-place using your custom logic:
List<String> names = new ArrayList<>(Arrays.asList("Charlie", "Alice", "Bob"));
Collections.sort(names, Comparator.reverseOrder());
// names is now ["Charlie", "Bob", "Alice"]
Arrays.sort(T[], Comparator)
Sorts an array using the provided Comparator:
String[] words = {"zebra", "apple", "mango"};
Arrays.sort(words, Comparator.naturalOrder());
// words is now ["apple", "mango", "zebra"]
Stream sorting
Use sorted(Comparator) in stream pipelines:
List<Integer> numbers = Arrays.asList(5, 2, 8, 1);
List<Integer> sorted = numbers.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
// sorted is [8, 5, 2, 1]
Without passing a Comparator, these methods fall back to natural ordering (requiring Comparable). By passing one, you gain complete control over sorting logic.
Key Takeaway: Pass Comparator instances to Collections.sort(), Arrays.sort(), and stream.sorted() to define custom sort order at runtime without modifying your classes or relying solely on natural ordering.