How to find maximum value from a Integer using stream in Java 8?
Solution 1:
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:
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
Solution 3:
Another version could be:
int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();