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.
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.
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.