The Stream min() method is used to select the minimum/smallest element in the Stream
according to the Comparator used for comparing the elements.
The Comparator
imposes a total ordering on the Stream elements which may not have a natural ordering.
1. Stream min() Method
1.1. Method Syntax
- The method takes a non-interfering, stateless Comparator to compare elements of the stream.
- It returns an Optional describing the maximum element of the stream, or an empty
Optional
if the stream is empty. - The
min()
method throws NullPointerException if the minimum element found isnull
.
1.2. Description
- This is a terminal operation. So stream cannot be used after this method is executed.
- Returns the minimum/smallest element of this stream according to the provided
Comparato
r. - This is a special case of a stream reduction.
- The method argument shall be a non-interfering, stateless
Comparator
. - The method returns an Optional describing the smallest element of this stream, or an empty
Optional
if the stream is empty. - It may throw NullPointerException if the smallest element is
null
.
2. Stream min() Examples
Example 1: Finding Smallest Element with Lambda Expression
Java example to find the minimum number from a stream of numbers using comparator as lambda expression.
Program output.
Example 2: Finding Smallest Element with Comparator
Java example to find the minimum number from a stream of numbers using custom comparator.
Program output.
Drop me your questions related to Java 8 Stream min() API in Java Stream API to find the smallest element in stream.
Happy Learning !!
Comments