summaryStatistics()方法可一次性获取流的计数、总和、平均值、最大值和最小值,Int/Long/DoubleSummaryStatistics分别对应int/long/double类型,需先用mapToInt/mapToLong/mapToDouble转换,空流时各值有特定默认返回,toString()提供格式化汇总,但不支持标准差、中位数等高级统计。

Java Stream API 的 summaryStatistics() 方法能一次性获取整数、长整型或双精度浮点数流的常用统计值,比如计数、总和、平均值、最大值和最小值。它比单独调用 count()、max() 等更高效,因为只需遍历一次流。
使用 IntSummaryStatistics 统计 int 流
对 int 类型数据,调用 mapToInt() 转换后使用 summaryStatistics():
- 必须先将流映射为
IntStream,否则编译不通过 - 返回
IntSummaryStatistics对象,提供getCount()、getSum()、getAverage()、getMax()、getMin()等方法 - 空流时,
getCount()为 0,getSum()为 0,getAverage()返回0.0(不是NaN),getMax()和getMin()返回Integer.MIN_VALUE和Integer.MAX_VALUE—— 注意判空处理
示例:
ListIntSummaryStatistics stats = numbers.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
System.out.println("count: " + stats.getCount()); // 5
System.out.println("sum: " + stats.getSum()); // 25
System.out.println("avg: " + stats.getAverage()); // 5.0
LongSummaryStatistics 和 DoubleSummaryStatistics 类似但类型不同
对应 long 和 double 数据,分别用 mapToLong() 和 mapToDouble():
立即学习“Java免费学习笔记(深入)”;
-
LongSummaryStatistics:getSum()返回long,避免int溢出问题 -
DoubleSummaryStatistics:getAverage()返回double,支持小数;空流时getMax()/getMin()分别返回Double.NEGATIVE_INFINITY和Double.POSITIVE_INFINITY - 三者都重写了
toString(),直接打印可看到格式化汇总(如IntSummaryStatistics{count=5, sum=25, min=1, average=5.000000, max=9})
配合 filter 或其他中间操作灵活统计
可在生成统计前加入条件筛选,比如只统计正数、偶数或满足业务规则的数据:
- 统计列表中大于 10 的数字的平均值和个数:
list.stream().filter(x -> x > 10).mapToInt(...).summaryStatistics() - 结合
flatMap处理嵌套结构(如 List- >)再统计总和与均值
- 注意:所有中间操作(如
filter、map)都在终端操作summaryStatistics()触发时一次性执行,不会额外遍历
不支持标准差、中位数等高级指标
summaryStatistics() 提供的是基础五数摘要,如需方差、标准差、中位数、百分位数等,需自行计算或借助第三方库(如 Apache Commons Math 的 DescriptiveStatistics):
- 标准差可通过先求平均,再用
mapToDouble(x -> Math.pow(x - avg, 2))求方差后开方实现 - 中位数需先收集到列表并排序,不适合大数据流(会失去流式处理优势)
- 若需复杂统计,建议考虑
Collectors.collectingAndThen配合自定义收集器,或切换到专业分析工具


















