如何使用 Java 8 中的流从整数中找到最大值?

How to find maximum value from a Integer using stream in Java 8?

我有一个 Integer list 的列表,我想要 list.stream() 的最大值。

最简单的方法是什么?我需要比较器吗?

您可以将流转换为 IntStream:

OptionalInt max = list.stream().mapToInt(Integer::intValue).max();

或指定自然顺序比较器:

Optional<Integer> max = list.stream().max(Comparator.naturalOrder());

或者使用reduce操作:

Optional<Integer> max = list.stream().reduce(Integer::max);

或使用收集器:

Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));

或使用 IntSummaryStatistics:

int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();
int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));

另一个版本可能是:

int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();

正确代码:

int max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));

int max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);

你可以使用 int max= Stream.of(1,2,3,4,5).reduce(0,(a,b)->Math.max(a,b)) ; 适用于正数和负数

使用流和减少

Optional<Integer> max = list.stream().reduce(Math::max);

您还可以使用以下代码片段:

int max = list.stream().max(Comparator.comparing(Integer::valueOf)).get();

另一种选择:

list.sort(Comparator.reverseOrder()); // max value will come first
int max = list.get(0);  
int value = list.stream().max(Integer::compareTo).get();
System.out.println("value  :"+value );