Sum values in array

This example will show how to compute or calculate the sum of all elements in an array using java, java 8 and apache commons techniques.

Setup

Using a standard java technique, we will iterate over the primitive double array using a enhanced for loop. Each iteration will add the element to the total which will result to the sum of all numbers in the array.

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

Straight up Java

@Test
public void sum_values_in_array_with_java () {

    double total = 0;
    for (double element : numbers) {
        total += element;
    }
    assertEquals(389, total, 0);
}

Java 8

Java 8 Streams contains reduce operations which provides an internal implementation of sum that enables a cleaner, more maintainable, and eloquent of way of handling summing all elements in an array than above. If you choose, stream.parallel will enable the internal implementation to choose to perform the reduce operation in parallel. Looking for more than just sum, DoubleSummaryStatistics example is a class that calculates all statistics such as average, count, min max and sum.

@Test
public void sum_values_in_array_with_java_8 () {

    double total = DoubleStream.of(numbers).sum();

    assertEquals(389, total, 0);

    // or

    double total2 = Arrays.stream(numbers).sum();

    assertEquals(389, total2, 0);
}

Apache Commons

StatUtils, an appache commons class, provides static methods for computing statistics on primitive double arrays. We will call the sum method which will calculate the sum of the values in the input array.

@Test
public void sum_values_in_array_with_apache_commons () {

    double total = StatUtils.sum(numbers);
    assertEquals(389, total, 0);
}

ReactiveX - RXJava

Using the Observable.from method will convert the List to an Observable then emit the items to the sequence. Next, the sumInteger part of Mathematical and Aggregate Operators will sum all the Integers emitted by the source. In addition to sumInteger, sumLong, sumFloat and sumDouble exist as well.

@Test
public void find_min_value_in_array_with_rxjava() {

    Observable<Integer> sumTotal = Observable
            .from(Arrays.asList(1, 24, 45, 62, 85, 8, 91, 3, 5, 56, 9));
    sumInteger(sumTotal).subscribe(System.out::println); // 389
}