Course contentsShow
← Java
Lesson 1333 of 2,87030. Comparable and ComparatorFree lesson

Comparator.naturalOrder and Comparator.reverseOrder

Use built-in factory methods to obtain Comparators for natural ordering and its reverse without writing custom logic.

Comparator.naturalOrder and Comparator.reverseOrder

What you'll learn: How to use Java's built-in factory methods to create Comparators without writing custom logic.


The Core Idea

Sometimes you need a Comparator object even when you just want natural ordering or its reverse. Instead of writing boilerplate code like (a, b) -> a.compareTo(b), Java provides factory methods that return ready-made Comparators for these common scenarios.

Comparator.naturalOrder() returns a Comparator that sorts elements according to their natural ordering (as defined by their Comparable implementation). This is equivalent to calling compareTo() directly.

Comparator.reverseOrder() returns a Comparator that sorts in the opposite direction—descending order instead of ascending.

When to Use These Methods

These factory methods shine when an API requires a Comparator object explicitly. For example:

List<String> words = Arrays.asList("banana", "apple", "cherry");

// Sort alphabetically using natural order
words.sort(Comparator.naturalOrder());
// Result: [apple, banana, cherry]

// Sort reverse alphabetically
words.sort(Comparator.reverseOrder());
// Result: [cherry, banana, apple]

Think of these methods as pre-built templates—like choosing "sort A-Z" or "sort Z-A" from a menu rather than configuring the sort yourself.

Why Not Just Use Collections.sort()?

When you call Collections.sort(list) or list.sort(null), Java uses natural ordering automatically. But when you need to pass a Comparator explicitly—perhaps to a method parameter or to chain with other Comparator operations—these factory methods provide clean, readable code.

Key Takeaway:
Comparator.naturalOrder() and Comparator.reverseOrder() provide clean, reusable Comparators for standard and reversed natural ordering without custom implementations.