Sum values in list

This example will show how to sum elements of an arraylist made of numbers using java, java 8 and apache commons. If you are looking for more than just sum, the same reduction technique can be found in average of an ArrayList, finding min of numbers in ArrayList and finding the max value in ArrayList. In a comparable example we demonstrate how to sum numbers in an arraylist using groovy.

Setup

private static List<Double> NUMBERS_FOR_SUM;

@Before
public void setup () {
    NUMBERS_FOR_SUM = new ArrayList<Double>();
    NUMBERS_FOR_SUM.add(new Double(10));
    NUMBERS_FOR_SUM.add(new Double(10));
    NUMBERS_FOR_SUM.add(new Double(10));
    NUMBERS_FOR_SUM.add(new Double(10));
    NUMBERS_FOR_SUM.add(new Double(10));
    NUMBERS_FOR_SUM.add(new Double(10));
    NUMBERS_FOR_SUM.add(new Double(10));
    NUMBERS_FOR_SUM.add(new Double(10));
    NUMBERS_FOR_SUM.add(new Double(10));
    NUMBERS_FOR_SUM.add(new Double(10));
}

Straight up Java

This snippet will sum all digits in an ArrayList using a standard java technique. We will initialize a variable sum and with each iteration of the java 5 for loop add the element to the total which will result to the sum of all numbers in the list.

@Test
public void sum_values_in_list_java () {
    
     Double sum = new Double(0); 
     for (Double i : NUMBERS_FOR_SUM) {
         sum = sum + i;
     }
         
    assertEquals(100, sum, 0);
}

Java 8

This snippet will sum all values in an ArrayList using java 8 techniques. 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 ArrayList. If you are looking to calculate all reduction operations, DoubleSummaryStatistics example is a class which will calculate all statistics such as average, count, min max and sum.

@Test
public void sum_values_in_list_java_8() {

    double sum = NUMBERS_FOR_SUM.stream().reduce(0d, (a, b) -> a + b);

    assertEquals(100, sum, 0);

    // or

    double sum2 = NUMBERS_FOR_SUM
            .stream()
            .mapToDouble(Double::doubleValue)
            .sum();

    assertEquals(100, sum2, 0);
}

Apache Commons

This snippet will use apache commons to sum all of the values in an ArrayList using StatUtils which provides static methods for computing statistics.

@Test
public void sum_values_in_list_apache() {

    double[] arrayToSume = ArrayUtils.toPrimitive(NUMBERS_FOR_SUM
            .toArray(new Double[NUMBERS_FOR_SUM.size()]));

    double sum = StatUtils.sum(arrayToSume);

    assertEquals(100, sum, 0);
}