问题
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?
回答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();
回答2:
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
回答3:
Another version could be:
int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
回答4:
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);
回答5:
With stream and reduce
Optional<Integer> max = list.stream().reduce(Math::max);
回答6:
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);
回答7:
int value = list.stream().max(Integer::compareTo).get();
System.out.println("value :"+value );
回答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
来源:https://stackoverflow.com/questions/31378324/how-to-find-maximum-value-from-a-integer-using-stream-in-java-8