Using Natural Ordering with min and max
What you'll learn: How to use Comparator.naturalOrder() and Comparator.reverseOrder() to easily find minimum and maximum values for types that already know how to compare themselves.
The Natural Ordering Shortcut
In the previous lesson, you learned that min() and max() require a Comparator to know how to compare elements. For types like Integer, String, and Double that implement Comparable, you could write your own comparator—but there's a much simpler way.
Comparator.naturalOrder() creates a comparator that uses the type's built-in ordering. For numbers, that's ascending order (1, 2, 3...). For strings, it's alphabetical (A, B, C...).
Comparator.reverseOrder() flips that ordering around.
Using Natural Order
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9);
Optional<Integer> smallest = numbers.stream()
.min(Comparator.naturalOrder());
// Result: Optional[1]
Optional<Integer> largest = numbers.stream()
.max(Comparator.naturalOrder());
// Result: Optional[9]
Using Reverse Order
List<String> words = Arrays.asList("zebra", "apple", "mango");
Optional<String> firstAlphabetically = words.stream()
.min(Comparator.naturalOrder());
// Result: Optional[apple]
Optional<String> lastAlphabetically = words.stream()
.max(Comparator.naturalOrder());
// Or equivalently:
Optional<String> lastAlphabetically2 = words.stream()
.min(Comparator.reverseOrder());
// Both result in: Optional[zebra]
Think of It This Way
Natural ordering is like asking "how would I sort this in Excel?" Numbers go from smallest to largest, strings go A-Z. Using Comparator.naturalOrder() means "use that default sorting rule." Using reverseOrder() means "flip it around."
Key Takeaway: Use Comparator.naturalOrder() with min() and max() for types like Integer, String, and Double that have built-in comparison logic; use Comparator.reverseOrder() to flip the ordering without writing custom comparison code.