【问题标题】:Calculate average or take in an ArrayList as a parameter to a function计算平均值或将 ArrayList 作为函数的参数
【发布时间】:2012-05-05 21:06:15
【问题描述】:

有没有内置方法来计算整数 ArrayList 的平均值?

如果没有,我可以通过获取 ArrayList 的名称并返回其平均值来创建一个函数吗?

【问题讨论】:

  • 无....是的....

标签: java function arraylist average


【解决方案1】:

其实很简单:

// 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&lt;Integer&gt;

【讨论】:

  • @esej 不一定,仅当总和大于 Integer.MAX_VALUE 时。可以肯定的是,我编辑了我的答案以使用long。除此之外,我认为 OP 真的 不需要为此将总和存储在 BigInteger 中。
  • 我认为正确的说法应该是:“这可能会溢出”。
【解决方案2】:

如果你想比平均水平多一个计算机,我建议在 CERN 开发的Colt 库支持许多统计功能。请参阅 BinFunctions1DDoubleMatrix1D。 替代方案(基于最近的代码)可能是commons-math

DescriptiveStatistics stats = new DescriptiveStatistics();
for( int i = 0; i < inputArray.length; i++)
{
    stats.addValue(inputArray[i]);
}
double mean = stats.getMean();

【讨论】:

    【解决方案3】:

    即将推出,使用 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);
    

    【讨论】:

      【解决方案4】:

      不,没有。您可以简单地遍历整个列表以添加所有数字,然后简单地将总和除以数组列表的长度。

      【讨论】:

        【解决方案5】:

        您可以使用Apache Commons 库中的'mean'

        【讨论】:

          猜你喜欢
          • 2017-09-26
          • 2021-02-14
          • 2013-01-14
          • 1970-01-01
          • 1970-01-01
          • 2017-03-03
          • 1970-01-01
          • 2013-10-25
          • 2016-10-07
          相关资源
          最近更新 更多