我有一个列表Integer
list
,并从list.stream()
我想要的最大值。最简单的方法是什么?我需要比较器吗?
您可以将流转换为IntStream
:
OptionalInt max = list.stream().mapToInt(Integer::intValue).max();
或指定自然顺序比较器:
Optional<Integer> max = list.stream().max(Comparator.naturalOrder());
或使用减少操作:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句