Java 流操作高级概念全解析
1. 汇总统计
在处理整数流时,我们可以获取其最大值。若流为空,会抛出异常。示例代码如下:
private static int max(IntStream ints) {
OptionalInt optional = ints.max();
return optional.orElseThrow(RuntimeException::new);
}
这里使用 OptionalInt 来处理可能为空的流。若 optional 包含值则返回,否则抛出 RuntimeException 。
接下来,我们要计算流的范围,即最大值减去最小值。但 min() 和 max() 是终端操作,不能对同一流执行两次终端操作。不过,原始流提供了汇总统计功能来解决这个问题。
private static int range(IntStream ints) {
IntSummaryStatistics stats = ints.summaryStatistics();
if (stats.getCount() == 0) throw new RuntimeException();
return stats.getMax() - stats.getMin();
}
汇总统计包含以下
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



