Averaging an array in Java

Averaging the values of an array in java is similar to averaging in an arraylist or other collection of objects. The examples are implemented with java, java 8, guava, and apache commons to explain how to find the arithmetic mean of a numeric array.

Using the naïve method, we'll traverse the array of integers with the for each loop. A variable "sum" adds to each iteration the value of the current position, then "sum" is divided by the size of the array. That's how we find the mean.

public class average_array {

public static void main(String[] args) {

int array[] = {16, 5, 13, 54, 17, 2, 38, 42, 67};

for (int number:array)
System.out.print(number+" ");

int sum = 0;
for(int i = 0; i < array.length; i++){
sum += array[i];
}
average float = (float) sum /array.length;

System.out.print("\nAverage = "+average);
}
}
Runtime:

16 5 13 54 17 2 38 42 67 
Average=28.222221

Java 8

In java 8, The JDK provides a set of operations that help reduce the number of statements, unlike the previous example, the average of an array is done in a single statement.

public void moyenne_tableau_java8 () {
OptionalDouble mean = Arrays.stream(TabNumbers).average();
}

Google Guava

Google Guava contains the java.lang.Math class that allows you to process int and double.

public static float moyenne_tableau_guava (int array[]) {
float average = (float) DoubleMath.mean(array);
return average;
}

Apache Commons

Apache commons contains a mathematical library that simplifies long calculations.

public static float moyenne_tableau_apache_commons (int array[]) {
Mean mean = new Mean();
float average = mean.evaluate(array);
return average;
}
Resources:
Javadoc:  DoubleStream Interface
Apache commons:  Mean.java class