可以通过遍历List,将每个元素的特定字段值累加起来,然后除以List的大小得到平均值。

假设List的泛型是T,T类中有一个字段是field,可以这样实现:

public static <T> double getAverage(List<T> list, Function<T, Double> fieldExtractor) {
    double sum = 0;
    for (T t : list) {
        sum += fieldExtractor.apply(t);
    }
    return sum / list.size();
}

使用示例:

假设有一个Student类,有一个字段是score,可以这样调用getAverage方法:

List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 85));
students.add(new Student("Bob", 90));
students.add(new Student("Charlie", 75));

double averageScore = getAverage(students, Student::getScore);
System.out.println("Average score: " + averageScore);

其中,Student类的定义如下:

public class Student {
    private String name;
    private double score;

    public Student(String name, double score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public double getScore() {
        return score;
    }
}

运行结果为:

Average score: 83.33333333333333
``
java List 取泛型的某字段的平均值

原文地址: https://www.cveoy.top/t/topic/icDZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录