Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.min()

Finds the smallest element of a stream.

Available since: Java 8

Syntax

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

Parameters

ParameterTypeDescription
comparatorComparator<? super T>The comparison rule.

Return value

Optional<T>The smallest element, or an empty `Optional`.

Examples

The shortest word:

void main() {
    String shortest = Stream.of("banana", "fig", "cherry")
        .min(Comparator.comparingInt(String::length))
        .orElseThrow();
    IO.println(shortest);
    IO.println(IntStream.of(5, 3, 8).min().getAsInt());
}

Output:

fig
3

Notes

Like max(), it returns an empty Optional on an empty stream. Numeric streams have a version without a comparator that returns OptionalInt, OptionalLong or OptionalDouble.

See also

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.