Let us discuss multiple ways of adding the values of a list of integers. The traditional method to get the sum of a list in Java is to use the ‘for’ loop, but that’s a bit costly. Many utility methods can do the same with much grace. Java 8 also defines a new method, which we will discuss later in this article.
All the methods apply to LinkedList and ArrayList both. We will use ArrayList in the examples, and you can try the same with LinkedList too.
How to get sum of a list in Java using for loop
First, let us populate a small list:
List<Integer> myArrList = new ArrayList<Integer>(); myArrList.add(1); myArrList.add(2); myArrList.add(3); myArrList.add(4); myArrList.add(5);
Now, declare an integer sum which we will calculate using the for loop:
int sum = 0; // Now let's get the values - you can do the same with a while loop also for(int i=0; i < myArrList.size(); i++) sum+=myArrList.get(i); System.out.println(sum);
You can do the same with a while loop using the methods hasNext() and next().
How to get sum of a list in Java using Apache commons utility
Using the sum method is easy, but you have to include the Apache Commons Mathematics Library. Next, we have to import the same into our class:
We use the StatUtils class to get the sum. We have to convert the list into an array because the method sum accepts an array:
Integer myArr = (Integer) myArrList.toArray(); int sum1 = (int)StatUtils.sum(myArr);
We have to typecast the return value because the method is for doubles and returns a double type.
How to get sum of a list in Java using Streams (Java 8)
This is the most efficient method as of Java8 and provides multiple methods. We will implement each of them one by one. Import the following:
import java.util.stream.Stream; import java.util.stream.Collectors;
We use the sum() method to get the sum using the stream class:
Integer sum2 = myArrList.stream().mapToInt(Integer::intValue).sum();
We can also use the reduce() method of stream filter. It applies a binary accumulator. The first operand is the result of the previous application, and the second is the current stream:
sum = myArrList.stream().reduce(0, (a, b) -> a + b);
Another method of stream, Stream.collect(), uses the Collector class for these terminal operations, which we imported earlier.
sum = myArrList.stream().collect(Collectors.summingInt(Integer::intValue));
We have discussed the various ways to get the sum of int values from a list in java. The same methods can be used for long, float, double as well. Although we have used a static list in this example with only a few values, in a real-world case, there may be huge values, which may lead to an overflow (a long value instead of int). You should always remember to handle such errors or make type declarations accordingly.
People are also reading: