Stream.min()
Finds the smallest element of a stream.
Available since: Java 8
Syntax
Optional<T> min(Comparator<? super T> comparator)Parameters
| Parameter | Type | Description |
|---|---|---|
| comparator | Comparator<? 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
3Notes
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
- Stream.max() — Finds the largest element of a stream.
- Collections.min() — Finds the smallest element of a collection.
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.