The 30 second answer
For a simple max I use stream max with natural order. When I also need count, sum, and average, I map to IntStream and call summaryStatistics in one pass. On an empty stream getMax returns Integer.MIN_VALUE, which is a trap worth calling out.
Optional<Integer> max = nums.stream().max(Comparator.naturalOrder());
IntSummaryStatistics st = nums.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
st.getMax();
st.getMin();summaryStatistics() gives count, sum, min, max, and average in one pass. On empty input getMax() returns Integer.MIN_VALUE and getMin() returns Integer.MAX_VALUE — mention that trap.
Sources:
Sources (0)
See inline citations in the answer above.