I have a list of Integer
list
and from the list.stream()
I want the maximum value.
What is the simplest way? Do I need comparator?
Calling stream() method on the list to get a stream of values from the list. Calling mapToInt(value -> value) on the stream to get an Integer Stream. Calling max() method on the stream to get the max value. Calling orElseThrow() to throw an exception if no value is received from max()
With the introduction of Stream with Java 8, we can convert the array into the corresponding type stream using the Arrays. stream() method. Then we can call the max() and min() method, which returns the maximum and minimum element of this stream as OptionalInt .
min method we get the minimum element of this stream for the given comparator. Using Stream. max method we get the maximum element of this stream for the given comparator. The min and max method both are stream terminal operations.
You may either convert the stream to IntStream
:
OptionalInt max = list.stream().mapToInt(Integer::intValue).max();
Or specify the natural order comparator:
Optional<Integer> max = list.stream().max(Comparator.naturalOrder());
Or use reduce operation:
Optional<Integer> max = list.stream().reduce(Integer::max);
Or use collector:
Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));
Or use IntSummaryStatistics:
int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
Another version could be:
int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With