What is the Stream min() method in Java?
The Stream min() method will return an Optional that contains the smallest value of the stream. The smallest values are evaluated based on the passed Comparator argument.
- If the stream is empty, then an empty
Optionalis returned. - If the minimum value is
null, thenNullPointerExceptionis thrown. - The
minmethod is a .terminal operation The stream cannot be used after this is called.
Example
import java.util.Arrays;import java.util.List;import java.util.Optional;public class Main {public static void main(String[] args){List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, -10);Optional<Integer> min;min = list.stream().min((a, b) -> a -b );System.out.println("The list is " + list);System.out.println("Minumum value of the list is " + min.get());}}
In the above code, we have used the Stream min() method on the list stream by passing a comparator to get the minimum value of the list. The minimum value can be retrived from the list by calling the get method of the returned Optional.
Calling min on empty stream
If the stream is empty, then an empty Optional is returned.
import java.util.List;import java.util.ArrayList;import java.util.Optional;public class Main {public static void main(String[] args){List<Integer> list = new ArrayList<Integer>();Optional<Integer> min;min = list.stream().min((a, b) -> a -b );System.out.println("The list is " + list);System.out.println("Checking if the value present in the Optional - " + min.isPresent());}}