Stream.max()
Finds the largest element of a stream.
Available since: Java 8
Syntax
Optional<T> max(Comparator<? super T> comparator)Parameters
| Parameter | Type | Description |
|---|---|---|
| comparator | Comparator<? super T> | The comparison rule. |
Return value
Optional<T>The largest element, or an empty `Optional`.
Examples
The oldest user:
record User(String name, int age) {}
void main() {
var users = List.of(new User("Anna", 31), new User("Oleg", 45), new User("Ivan", 19));
users.stream()
.max(Comparator.comparingInt(User::age))
.ifPresent(u -> IO.println(u.name()));
IO.println(Stream.of(4, 9, 2).max(Integer::compare).get());
}Output:
Oleg
9Notes
On a Stream the method needs a comparator. On numeric streams (IntStream) max() takes no arguments and returns an OptionalInt. An empty stream gives an empty Optional, not an exception.
See also
- Stream.min() — Finds the smallest element of a stream.
- Collections.max() — Finds the largest element of a collection.
- Comparator.comparing() — Creates a comparator that compares objects by one key.
Related recipes
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.