This post will discuss how to calculate the sum of all elements in a List in Java.

1. IntStream’s sum() method

A simple solution to calculate the sum of all elements in a List is to convert it into IntStream and call sum() to get the sum of elements in the stream. There are several ways to get IntStream from Stream<Integer> using mapToInt() method.

 
1. Using method reference Integer::intValue

Download  Run Code

 
2. Using method reference Integer::valueOf

Download  Run Code

 
3. Using Lambda expression i -> i

Download  Run Code

2. Reduce operation

Another solution is to perform reduce operation to perform the addition.

Download  Run Code

 
We can simplify the above code using method reference Integer::sum, as shown below:

Download  Run Code

 
The code can be further simplified by removing Optional:

Download  Run Code

3. Using IntSummaryStatistics

Finally, we can get IntSummaryStatistics instance from IntStream, which has getSum() method to get the sum of values in it.

Download  Run Code

4. Naive solution

We can even write a custom routine to calculate the sum of all elements in a List using a for-loop, as shown below:

Download  Run Code

That’s all about calculating the sum of all elements in a List in Java.