Collectors.averagingInt用于计算集合中整型属性的平均值,接收ToIntFunction函数式接口,提取int值并返回Double类型的平均数;示例中通过Employee类的getAge方法获取年龄,使用stream结合collect计算平均年龄,输出30.0;空集合处理时返回0.0,需注意与业务上“无数据”的区分;类似方法有averagingLong和averagingDouble,根据字段类型选择使用,如double类型的工资应使用averagingDouble;该收集器简洁高效,适合日常开发中的整型数据统计。

在Java中,Collectors.averagingInt 是一个非常实用的收集器,用于计算集合中元素某个整数值属性的平均值。它属于 java.util.stream.Collectors 类的一部分,常配合 Stream API 使用,让数据统计变得简洁高效。
Collectors.averagingInt 介绍
averagingInt 接收一个 ToIntFunction 函数式接口作为参数,该函数用于从集合中的每个元素提取一个 int 类型的值,然后计算这些值的算术平均数,返回类型为 Double。
方法签名如下:
public static <t> Collector<t double> averagingInt(ToIntFunction super T> mapper)</t></t>
立即学习“Java免费学习笔记(深入)”;
基本使用示例
假设我们有一个员工类 Employee,需要计算所有员工年龄的平均值。
class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
// getter 方法
public int getAge() { return age; }
}
创建员工列表并计算平均年龄:
当用户要求为 Java 代码添加注释、修改注释、审查注释、整理注释格式,或要求按照代码注释规范处理 Java 文件时,使用本技能。本技能用于统一生成和维护 Java 类注释模板、按 Git 对比 release 判断版本号、补充每行代码上方中文块注释、调整注释空行规则,并保持 Java 文件 UTF-8 无 BOM 编码。典型触发场景包括:补充类注释、更新 @version、检查 @author 来源、整理行尾注释、把注释放到代码上一行、检查注释是否符合规范、构建前检查 Java 注释风格。
List
new Employee("Alice", 30),
new Employee("Bob", 25),
new Employee("Charlie", 35)
);
Double averageAge = employees.stream()
.collect(Collectors.averagingInt(Employee::getAge));
System.out.println("平均年龄: " + averageAge); // 输出:30.0
处理空集合的情况
如果集合为空,averagingInt 会返回 0.0,而不是抛出异常。这一点在实际开发中需要注意,避免误判。
例如:
List
Double avg = emptyList.stream().collect(Collectors.averagingInt(Employee::getAge));
System.out.println(avg); // 输出:0.0
如果业务上需要区分“无数据”和“平均值为0”,建议额外判断集合是否为空。
与其他平均值方法对比
除了 averagingInt,还有两个类似的方法:
- averagingLong:用于 long 类型,返回 Double
- averagingDouble:用于 double 类型,返回 Double
选择哪个方法取决于你要提取的字段类型。比如工资是 double 类型时,应使用 averagingDouble。
例如计算工资平均值:
Double avgSalary = employees.stream()
.collect(Collectors.averagingDouble(e -> e.getSalary()));
基本上就这些。Collectors.averagingInt 简洁明了,适合快速统计整型字段的平均值,结合 Stream 使用可读性高,是日常开发中处理集合聚合操作的好工具。















