Collectors.averagingInt用于计算流中元素的整数平均值,接收ToIntFunction参数提取int值,返回double类型结果。1. 可计算对象列表中某int字段的平均值,如学生分数。2. 适用于整数集合的平均值统计,支持方法引用或lambda表达式。3. 流为空时返回0.0,不抛异常,适合简单平均场景,性能良好,内部一次遍历完成求和与计数。
在Java中,Collectors.averagingInt 是 java.util.stream.Collectors 类提供的一个归约操作方法,用于计算流中元素的整数平均值。它适用于从对象集合中提取 int 值并求平均,返回结果是 dou 类型。
ble
Collectors.averagingInt 接收一个 ToIntFunction 函数式接口作为参数,该函数负责从每个元素中提取一个 int 值。然后系统会自动计算这些值的算术平均数。
常见使用场景包括:
假设有一个表示学生信息的类:
class Student {
String name;
int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
// getter 方法
public int getScore() {
return score;
}
}
现在有一个学生列表,想计算所有学生成绩的平均分:
Liststudents = Arrays.asList( new Student("Alice", 85), new Student("Bob", 90), new Student("Charlie", 78) ); double averageScore = students.stream() .collect(Collectors.averagingInt(Student::getScore)); System.out.println("平均成绩: " + averageScore); // 输出: 平均成绩: 84.33333333333333
如果集合本身就是 Integer 或 int 类型的数据,可以直接使用方法引用或 lambda 表达式:
Listnumbers = Arrays.asList(10, 20, 30, 40); double avg = numbers.stream() .collect(Collectors.averagingInt(x -> x)); System.out.println("平均值: " + avg); // 输出: 平均值: 25.0
这里 x -> x 表示将每个 Integer 元素自身作为 int 值提取出来参与计算。
使用 averagingInt 时需要注意以下几点:
double,便于处理小数部分0.0,不会抛出异常,但需注意是否符合业务逻辑Collectors.summarizingInt
基本上就这些。掌握 Collectors.averagingInt 能让你在处理集合数据时更简洁高效地完成平均值计算。