Sum first N values in list

This example will show how to sum the first N numbers within arraylist in java. In the set up we will define an arraylist of 9 elements containing random numbers. In each snippet below we will take the first 5 elements and then calculate the sum of the Integer values in the list.

Setup

List<Integer> numbers;

@Before
public void setUp() {

    numbers = new ArrayList<>();

    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
    numbers.add(4);
    numbers.add(5);
    numbers.add(6);
    numbers.add(7);
    numbers.add(8);
    numbers.add(9);

}

Straight up Java

Using standard java technique we will calculate the sum of the first N numbers. We will declare a variables sumNValues and iterate over the array list using a for loop adding each element until we reach the the 6th element.

@Test
public void sum_n_values_java() {

    int sumNValues = 0;
    for (int x = 0; x < 5; x++) {
        sumNValues += numbers.get(x);
    }

    assertEquals(15, sumNValues);
}

Java 8

Using java 8 syntax we will calculate the sum of the first 5 consecutive numbers from an arraylist. We will first convert the arraylist to a IntStream, a special stream for handling primitive values, by calling the mapToInt function which will apply the Integer::intValue to each element. We will then limit the number of elements to 5 and then call the sum and calculate the sum of elements. The sum is a stream reduction operation similar to count, max, min and average. If you need more than just the sum, you could look to the IntSummaryStatistics which find all reduction operations in one object.

@Test
public void sum_n_values_java8() {

    int sumXValues = numbers.stream().mapToInt(Integer::intValue).limit(5)
            .sum();

    assertEquals(15, sumXValues);
}