Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find maximum value from a Integer using stream in Java 8?

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?

like image 215
pcbabu Avatar asked Jul 13 '15 08:07

pcbabu


People also ask

How do you find the maximum value of a stream?

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()

How do you find the maximum in an array using stream?

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 .

How do you use max and min in stream?

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.


3 Answers

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();
like image 73
Tagir Valeev Avatar answered Oct 08 '22 21:10

Tagir Valeev


int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
like image 13
Gripper Avatar answered Oct 08 '22 23:10

Gripper


Another version could be:

int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
like image 4
Olexandra Dmytrenko Avatar answered Oct 08 '22 22:10

Olexandra Dmytrenko