The Stream max()
method will return an Optional
that contains the largest value of the stream. The largest values are evaluated based on the passed Comparator argument.
Optional
is returned.null
, then NullPointerException
is thrown.max
method is a 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> max;max = list.stream().max((a, b) -> a - b );System.out.println("The list is " + list);System.out.println("Maximum value of the list is " + max.get());}}
In the above code, we have used the Stream max()
method on the list stream by passing a comparator to get the largest value of the list. The largest value can be retrieved by calling the get
method of the returned Optional
.
import java.util.Arrays;import java.util.List;import java.util.Optional;import java.util.Comparator;public class Main {public static void main(String[] args){List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, -10);Comparator<Integer> getMax;getMax = new Comparator<Integer>() {@Overridepublic int compare(Integer num1, Integer num2) {return num1 - num2;}};Optional<Integer> max;max = list.stream().max(getMax);System.out.println("The list is " + list);System.out.println("Maximum value of the list is " + max.get());}}
In the above code, we have created a getMax
comparator and passed it to the max
function, which will call return an Optional
with the max value.