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 使用,让数据统计变得简洁高效。
averagingInt 接收一个 ToIntFunction 函数式接口作为参数,该函数用于从集合中的每个元素提取一个 int 类型的值,然后计算这些值的算术平均数,返回类型为 Double。
方法签名如下:
public static <T> Collector<T, ?, Double> averagingInt(ToIntFunction<? super T> mapper)
立即学习“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; }
}
创建员工列表并计算平均年龄:
List<Employee> employees = Arrays.asList(
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<Employee> emptyList = Collections.emptyList();
Double avg = emptyList.stream().collect(Collectors.averagingInt(Employee::getAge));
System.out.println(avg); // 输出:0.0
如果业务上需要区分“无数据”和“平均值为0”,建议额外判断集合是否为空。
除了 averagingInt,还有两个类似的方法:
选择哪个方法取决于你要提取的字段类型。比如工资是 double 类型时,应使用 averagingDouble。
例如计算工资平均值:
Double avgSalary = employees.stream()
.collect(Collectors.averagingDouble(e -> e.getSalary()));
基本上就这些。Collectors.averagingInt 简洁明了,适合快速统计整型字段的平均值,结合 Stream 使用可读性高,是日常开发中处理集合聚合操作的好工具。
以上就是在Java中如何使用Collectors.averagingInt计算集合平均值_Collectors平均值实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号