Get sum of all elements of an array in Java 8

In this post, we will discuss how to get sum of all elements of an array in Java 8.


Java didn’t supply any build-in method for this simple task, unlike many other programming languages like std::accumulate in C++, array_sum() function in PHP, Enumerable.Sum method (IEnumerable<Int32>) in .NET Framework, etc. Before Java 8, the only solution is to iterate the given array using for-each loop and accumulate sum of all elements in a variable. This approach is illustrated here.

With introduction of Java 8 Streams API, we can easily get sum of all array elements using Stream.sum() method. To get Stream of array elements, we can use method. This method is overloaded for arrays of int, double and long type. It also has overloaded versions which allows you to get sum of elements between the specified indices of the array.


Download   Run Code

We can also call of() method of IntStream, DoubleStream, and LongStream class for int, double and long array respectively to get stream of array elements.


Download   Run Code

We can also use reduction to perform the addition operation.


Download   Run Code

Finally, we can use summaryStatistics() to get information about the elements of this stream like min/max element, average and total sum. It returns IntSummaryStatistics object which has getSum() method to get the sum of values.


Download   Run Code

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of