how to find maximum value from a Integer using stream in java 8?

pcbabu picture pcbabu · Jul 13, 2015 · Viewed 82.8k times · Source

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?

Answer

Tagir Valeev picture Tagir Valeev · Jul 13, 2015

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