Calculate average or take in an ArrayList as a parameter to a function

放肆的年华 提交于 2019-12-03 09:07:15
Óscar López

It's really simple:

// 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;
}

For even better performance, use int[] instead of ArrayList<Integer>.

If you want to computer later one more than the average I propose Colt library developed at CERN which supports many statistic functions. See BinFunctions1D and DoubleMatrix1D. An alternative (with a recent code basis) may be commons-math:

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

Comming soon, using lambda expressions and method references in JDK 8:

DoubleOperator summation = (a, b) -> a + b;
double average = data.mapReduce(Double::valueOf, 0.0,  summation) / data.size();
System.out.println("Avergage : " + average);
Edge

No there isn't. You can simply iterate over the complete list to add all the numbers and simply divide the sum by length of the array list.

dbf

You can use 'mean' from the Apache Commons library.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!