Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.max()

Finds the largest element of a stream.

Available since: Java 8

Syntax

Optional<T> max(Comparator<? super T> comparator)

Parameters

ParameterTypeDescription
comparatorComparator<? 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
9

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.