Computing average

Computing the average value of an array of numbers (in this case integers) can be implemented in two simple steps:

  1. Compute the sum of the elements from the array.
  2. 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.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.147.77