我有一个
Integer
类型的列表 list
,我想从 list.stream()
中获取最大值。最简单的方法是什么?我需要使用比较器吗?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
,那么可以使用 mapToInt(...).max().getAsInt()
或者 reduce(...).get()
方法链。 - Andrejsint max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
int maxUsingCollectorsReduce = list.stream().collect(Collectors.reducing(Integer::max)).get();
我认为另一种简单的方法是
IntSummaryStatistics statistics = List.of(1, 2, 3).stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
int max = statistics.getMax();
通过这个,你也可以getMin()
和其他一些像平均数之类的东西。可以通过提供适当的参数从其他流创建一个SummaryStatistics对象。
int value = list.stream().max(Integer::compareTo).get();
System.out.println("value :"+value );
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 max = list.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
或者
int max = list.stream().reduce(Integer.MIN_VALUE, Integer::max);
使用流和归约
Optional<Integer> max = list.stream().reduce(Math::max);
Integer::max
但这是完全相同的)。 - Didier L你也可以使用下面的代码在集合中找到最大元素:
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
Optional<Integer> max = intList.stream().max((a, b) -> a - b);
您可以使用 int max = Stream.of(1, 2, 3, 4, 5).reduce(0, (a, b) -> Math.max(a, b));,适用于正数和负数。
Integer.MIN_VALUE
开始,以使其适用于负数。 - Didier L
Collections.max
。 - Alexis C.