Java: 当我有一个对象集合时,有没有简单的方法来计算平均值?

Java: Is there an easy way to get an average when I have a collection of objects?

假设我有一个简单的对象:

public class Items {
    private static int 
        numItems,
        itemsInStock,
        itemsSold,
        //...
}

在代码的其他地方我有一个 ArrayList<Items>

是否有一种简单的方法可以获取 numItems / ItemsInStock 等的平均值/中值而不需要对对象的每个字段执行 for/each?

当前代码如下:

for (Items item: allItems) {
    if (item.field != null) { 
        temp += item.field;
    }
}
fieldAvg = temp / allItems.size();

使用流可以说更优雅:

double avg = allItems.stream().mapToInt(i -> i.itemsInStock).average().getAsDouble();
// Or any other field -------------------------^

您可以使用 IntSummaryStatistics,其所有功能 AverageSumMax、.. :

int[] itemsInStock = allItems.stream().mapToInt(Items::getItemsInStock).toArray();

IntSummaryStatistics stat = IntStream.of(itemsInStock).summaryStatistics();

double average = stat.getAverage();
int max = stat.getMax();
int min = statistics.getMin();
long count = statistics.getCount();
long sum = statistics.getSum();
....

这是一个使用函数式方法的可能解决方案。

import java.util.List;
import java.util.function.ToIntFunction;

public class Items {
    // it doesn't make sense for the members to be static
    private /* static */ int
        numItems,
        itemsInStock,
        itemsSold,
        //...

    private static double getAverage(List<Items> allItems, ToIntFunction<Items> getter) {
        // assumption: average should be a double
        // assumption: zero should be returned if no items passed
        return allItems.stream().mapToInt(getter).average().orElse(0.0);
    }

    private static void doAverageCalcs(List<Items> allItems) {
        double numItemsAverage = getAverage(allItems, t -> t.numItems);
        double itemsInStockAverage = getAverage(allItems, t -> t.itemsInStock);
        double itemsSoldAverage = getAverage(allItems, t -> t.itemsSold);
        // ...

        // do stuff with the averages
    }

    // the rest of the class' implementation goes here...
}