Computing the average value of an array of numbers (in this case integers) can be implemented in two simple steps:
- Compute the sum of the elements from the array.
- Divide this sum by the length of the array.
In code lines, we have the following:
public static double average(int[] arr) {
return sum(arr) / arr.length;
}
public static double sum(int[] arr) {
double sum = 0;
for (int elem: arr) {
sum += elem;
}
return sum;
}
The average of our integers array is 2.0:
double avg = MathArrays.average(integers);
In Java 8 functional style, the solution to this problem entails a single line of code:
double avg = Arrays.stream(integers).average().getAsDouble();
For third-party library support, please consider Apache Common Lang (ArrayUtil) and Guava's Chars, Ints, Longs, and other classes.