Calculate average of array

Similar to finding the average of an arraylist or collection, this example will use java, java 8, guava and apache commons to demonstrate how to find the average or the arithmetic mean of a numeric array of a primitive type.

Setup

double[] NUMBERS = {1, 24, 45, 62, 85, 8, 91, 3, 5, 56, 9};

Straight up Java

Using an imperative programming style, we will iterate over the numbers array using a for each loop. Each iteration will add to the total and then divide by the array length, thus finding the average.

@Test
public void calculate_average_of_array_java () {

    double total = 0;
    for (double element : NUMBERS) {
        total += element;
    }

    double average = total / NUMBERS.length;

    assertEquals(35.36363636363637, average, 0);
}

Java 8

In java 8, the JDK provides a series of reduction operations which provides an internal implementation. Unlike the example above, this abstraction enables a cleaner, more maintainable, and eloquent of way of handling finding the average of the array. If you choose, stream.parallel will enable the internal implementation to choose to perform the reduce operation in parallel. Looking for more than just the average, DoubleSummaryStatistics is a class that calculates all statistics such as average, count, min max and sum.

@Test
public void calculate_average_of_array_java8 () {

    OptionalDouble average = Arrays.stream(NUMBERS).average();

    assertEquals(35.36363636363637, average.getAsDouble(), 0);
}

Google Guava

Guava provides a class for arithmetic on doubles that is not covered by java.lang.Math.

@Test
public void calculate_average_of_array_guava () {

    double average = DoubleMath.mean(NUMBERS);

    assertEquals(35.36363636363637, average, 0);
}

Apache Commons

Apache commons Mean class will computes the arithmetic mean of a set of double values.

@Test
public void calculate_average_of_array_apache () {

    Mean mean = new Mean();
    double average = mean.evaluate(NUMBERS);

    assertEquals(35.36363636363637, average, 0);
}

ReactiveX - RXJava

Using the Observable.from method will convert the List to an Observable so it will emit the items to the sequence. Next, the averageInteger part of Mathematical and Aggregate Operators will compute the average of sequence returning a single item.

@Test
public void calculate_average_of_array_rxjava() {

    Observable<Integer> findAverage = Observable.from(Arrays.asList(1, 2,
            3, 4));
    averageInteger(findAverage).subscribe(System.out::println); // 2
}