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?
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();
Another version could be:
int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
With stream and reduce
Optional<Integer> max = list.stream().reduce(Math::max);
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
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
int value = list.stream().max(Integer::compareTo).get();
System.out.println("value :"+value );