How to find maximum value from a Integer using stream in Java 8?
Java 8Java StreamJava 8 Problem Overview
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?
Java 8 Solutions
Solution 1 - Java 8
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();
Solution 2 - Java 8
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
Solution 3 - Java 8
Another version could be:
int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
Solution 4 - Java 8
Correct code:
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
or
int max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);
Solution 5 - Java 8
You can also use below code snipped:
int max = list.stream().max(Comparator.comparing(Integer::valueOf)).get();
Another alternative:
list.sort(Comparator.reverseOrder()); // max value will come first
int max = list.get(0);
Solution 6 - Java 8
With stream and reduce
Optional<Integer> max = list.stream().reduce(Math::max);
Solution 7 - Java 8
int value = list.stream().max(Integer::compareTo).get();
System.out.println("value :"+value );
Solution 8 - Java 8
You could use int max= Stream.of(1,2,3,4,5).reduce(0,(a,b)->Math.max(a,b)); works for both positive and negative numbers