【发布时间】:2012-05-05 21:06:15
【问题描述】:
有没有内置方法来计算整数 ArrayList 的平均值?
如果没有,我可以通过获取 ArrayList 的名称并返回其平均值来创建一个函数吗?
【问题讨论】:
-
无....是的....
标签: java function arraylist average
有没有内置方法来计算整数 ArrayList 的平均值?
如果没有,我可以通过获取 ArrayList 的名称并返回其平均值来创建一个函数吗?
【问题讨论】:
标签: java function arraylist average
其实很简单:
// Better use a `List`. It is more generic and it also receives an `ArrayList`.
public static double average(List<Integer> list) {
// 'average' is undefined if there are no elements in the list.
if (list == null || list.isEmpty())
return 0.0;
// Calculate the summation of the elements in the list
long sum = 0;
int n = list.size();
// Iterating manually is faster than using an enhanced for loop.
for (int i = 0; i < n; i++)
sum += list.get(i);
// We don't want to perform an integer division, so the cast is mandatory.
return ((double) sum) / n;
}
要获得更好的性能,请使用int[] 而不是ArrayList<Integer>。
【讨论】:
long。除此之外,我认为 OP 真的 不需要为此将总和存储在 BigInteger 中。
如果你想比平均水平多一个计算机,我建议在 CERN 开发的Colt 库支持许多统计功能。请参阅 BinFunctions1D 和 DoubleMatrix1D。 替代方案(基于最近的代码)可能是commons-math:
DescriptiveStatistics stats = new DescriptiveStatistics();
for( int i = 0; i < inputArray.length; i++)
{
stats.addValue(inputArray[i]);
}
double mean = stats.getMean();
【讨论】:
即将推出,使用 JDK 8 中的 lambda 表达式和方法引用:
DoubleOperator summation = (a, b) -> a + b;
double average = data.mapReduce(Double::valueOf, 0.0, summation) / data.size();
System.out.println("Avergage : " + average);
【讨论】:
不,没有。您可以简单地遍历整个列表以添加所有数字,然后简单地将总和除以数组列表的长度。
【讨论】:
您可以使用Apache Commons 库中的'mean'。
【讨论】: