Finding Maximum Elements with max(Comparator)
What you'll learn: How to find the largest element in a stream using max() with a custom comparison strategy.
The Core Idea
The max() terminal operation finds the maximum element in a stream according to the comparison logic you provide via a Comparator. Since "maximum" depends entirely on how you define "greater than," you must supply this comparison rule. The method returns an Optional<T> because the stream might be empty (and thus have no maximum).
Think of max() like asking "Who's the winner?" in a competition—you need to define the judging criteria (your Comparator) to determine which element wins.
The Signature
Optional<T> max(Comparator<? super T> comparator)
Basic Usage
Finding the maximum of a stream of numbers using natural ordering:
Stream<Integer> numbers = Stream.of(3, 7, 2, 9, 5);
Optional<Integer> maximum = numbers.max(Comparator.naturalOrder());
maximum.ifPresent(System.out::println); // 9
With Custom Objects
Suppose you have a Person class and want to find the oldest person:
List<Person> people = List.of(
new Person("Alice", 30),
new Person("Bob", 45),
new Person("Carol", 28)
);
Optional<Person> oldest = people.stream()
.max(Comparator.comparingInt(Person::getAge));
oldest.ifPresent(p -> System.out.println(p.getName())); // Bob
Why Optional?
If your stream is empty, there's no maximum to return. The Optional forces you to handle this scenario:
Stream.<Integer>empty()
.max(Comparator.naturalOrder())
.orElse(-1); // Returns -1 if stream is empty
Key Takeaway: max() finds the largest element according to your custom Comparator, returning an Optional to safely handle empty streams—you define what "maximum" means through your comparison logic.