Java - 尝试计算来自 Getter 的平均值

Java - Trying to calculate the average of values coming from a Getter

我正在处理 Java 应用程序。
有一个Getter对应一个整型字段(score)。
我的目标是计算该字段的平均值。我决定制作一个数组,然后计算该数组的计数和总和。
但我真的陷入了 Java 语法和 "state of mind"..

这是我的片段:

    public void setPersonData2(List<Person> persons2) {
        // Try to make a count of the array
        int[] scoreCounter = new int[100]; // 100 is by default since we don't know the number of values
        for (Person p : persons2) {
            int score = p.getScoreTheo(); // Getter
            Arrays.fill(scoreCounter, score);
            // Try to delete all values equal to zero
            int[] scoreCounter2 = IntStream.of(scoreCounter).filter(i -> i != 0).toArray();
            // Calculate count
            int test = scoreCounter2.length;
            System.out.println(test);
        } 
}

你能帮帮我吗?

为什么计算简单平均值太复杂了?而且,我不明白你为什么需要数组。

int count = 0;
int sum = 0;
for (Person p : persons2) {
   ++count;
   sum += p.getScoreTheo();
}

double average = sum / (double)count;

使用流:

public void setPersonData2(List<Person> persons2) {
    double average = persons2.stream().mapToInt(p -> p.getScoreTheo()).average().getAsDouble();
    //[...]
}

它为空列表引发 NoSuchElementException

Stream API 有一个内置的平均函数。

double average = persons2.stream().collect(Collectors.averagingInt(person -> person.getScore()));