Course contentsShow
← Java
Lesson 1226 of 2,87028. Collections Utility ClassFree lesson

Sorting and Searching with Reverse Order

Apply Collections.reverseOrder to sort and search lists in descending order.

Sorting and Searching with Reverse Order

You'll learn how to use Collections.reverseOrder() to sort and search lists in descending order efficiently.

When you've been sorting lists in ascending order (smallest to largest), Java provides an elegant way to flip that entirely: Collections.reverseOrder(). This method returns a Comparator that imposes the reverse of natural ordering, making sorting and searching in descending order straightforward.

Why Reverse Order Matters

Imagine you're organizing exam scores—sometimes you want lowest-to-highest, but often you want highest-to-lowest to find the top performers. Rather than sorting ascending and manually reversing, you can sort in descending order directly.

Using reverseOrder() with Sorting

Pass Collections.reverseOrder() as the comparator to Collections.sort():

List<Integer> scores = new ArrayList<>(Arrays.asList(85, 92, 78, 95, 88));
Collections.sort(scores, Collections.reverseOrder());
// scores is now [95, 92, 88, 85, 78]

This works with any type that implements Comparable (like Integer, String, etc.).

Using reverseOrder() with Binary Search

Critical rule: When you search a list sorted with reverseOrder(), you must pass the same comparator to binarySearch():

List<String> names = new ArrayList<>(Arrays.asList("Alice", "Charlie", "Bob"));
Collections.sort(names, Collections.reverseOrder());
// names is now ["Charlie", "Bob", "Alice"]

int index = Collections.binarySearch(names, "Bob", Collections.reverseOrder());
// index is 1 (correct position in reverse-sorted list)

Without the comparator, binarySearch() assumes ascending order and returns incorrect results.

Key Takeaway: Use Collections.reverseOrder() to sort and search in descending order—just remember to pass it to both sort() and binarySearch() to maintain consistency.