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.


List<Integer> numbers;

public void setUp() {

    numbers = new ArrayList<>();



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.

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.

public void sum_n_values_java8() {

    int sumXValues =

    assertEquals(15, sumXValues);