Sum of array elements means the sum of all the elements(or digits) in the array. In other words, performing addition of array elements in java.
Array elements can be integers(int
) or decimal numbers(float
or double
).
There are different methods to calculate sum of elements in an array in java and this post discusses them all.
Method 1: Using for loop
This is a traditional and most commonly used approach where the array is iterated using a for loop.
In each iteration, the current array element is added to a variable which holds the sum of array elements.
This variable is initialized to 0 before the start of loop. Example,
public class ArraySumCalculator { public static void main(String[] args) { int[] array = { 1, 34, 67, 23, -2, 18 }; // variable to hold sum of array elements int sum = 0; // iterate using a for loop for (int counter = 0; counter < array.length; counter++) { // get current array element int element = array[counter]; // add element to sum sum += element; } System.out.println("Sum of array elements is: " + sum); } }
sum += element
is a short hand notation for sum = sum + element
Above program prints
Sum of array elements is: 141
for
loop in this program can also be replaced with a for-each
loop as shown below
for (int element: array) { sum += element; }
Method 2: Using Arrays.stream in java 8
This method uses stream concept introduced in java 8.
Call stream()
method on java.util.Arrays
class supplying it the array as argument. This method returns a stream of array elements.
Invoking sum()
method on this stream will provide the addition of all elements in the array. Example,
import java.util.Arrays; import java.util.stream.IntStream; public class ArraySumCalculator { public static void main(String[] args) { int[] array = { 1, 34, 67, 23, -2, 18 }; // get stream of elements IntStream stream = Arrays.stream(array); // add the elements in stream int sum = stream.sum(); System.out.println("Sum of array elements is: " + sum); } }
Note that calling stream
method returns a java.util.stream.IntStream
which is a stream of integer values.
This is because the array supplied to stream method was an integer array.
If the array is of type double, then the stream will be of java.util.stream.DoubleStream
Above code can also be reduced to a single line as below.
int sum = Arrays.stream(array).sum();
Output of this program is the same as the previous one.
Method 3: Using IntStream in java 8
Java 8 introduced java.util.stream.IntStream
which is a sequence of elements. It has an of
method taking an array as argument and returns a stream of the elements of array.
Calling sum()
method on the returned stream provides the sum of array elements. Example,
import java.util.stream.IntStream; public class ArraySumCalculator { public static void main(String[] args) { int[] array = { 1, 34, 67, 23, -2, 18 }; // get stream of elements IntStream stream = IntStream.of(array); // add the elements in stream int sum = stream.sum(); System.out.println("Sum of array elements is: " + sum); } }
Above code can be reduced to a one-liner as below.
int sum = IntStream.of(array).sum();
Method 4: Using reduction operation on stream
This method also uses a stream to find the sum of array elements. Once a stream is obtained, you can apply reduction on it.
From javadocs,
A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum or maximum of a set of numbers, or accumulating elements into a list.
java.util.stream.IntStream
has a reduce
method which takes 2 arguments. First is the identity element for the required operation. For addition operation, identity is 0.
Second argument is an argument of type java.util.function.InitBinaryOperator
which is a functional interface having a method applyAsInt
that applies an operation to the supplied operands.
Implementation to this method can be provided by using a Lambda expression. Example,
import java.util.stream.IntStream; public class ArraySumCalculator { public static void main(String[] args) { int[] array = { 1, 34, 67, 23, -2, 18 }; // get stream of elements IntStream stream = IntStream.of(array); // add the elements in stream using reduction int sum = stream.reduce(0,(e1, e2)-> e1 + e2); System.out.println("Sum of array elements is: " + sum); } }
Note the arguments to reduce()
method.
First is 0, which is the identity for addition.
Second is a lambda expression which says “apply addition operation on the supplied elements”.
This method will iterate over all the array elements and perform addition of those elements.
Above method can be reduced to a one-liner as.
int sum = IntStream. of(array). reduce(0,(element1, element2) -> element1+element2);
Method 5: Using Apache Math library
All the above methods are applicable to an array of integers. They can also be modified if the array is of decimal elements.
But if you specifically have an array of type double, then this method can be used to calculate the sum of its elements. Example,
import org.apache.commons.math3.stat.StatUtils; public class ArraySumCalculator { public static void main(String[] args) { double[] array = { 1, 34, 67, 23, -2, 18 }; int sum = (int)StatUtils.sum(array); System.out.println("Sum of array elements is: " + sum); } }
sum()
method from class org.apache.commons.math3.stat.StatUtils
of Apache Math library takes a double
array as argument and returns the sum of its elements.
This method only takes an array of type double as argument.
Note that we have explicitly casted the sum to an int
. This is because the return type of sum
is double
.
Casting is not required if you want the sum
in decimal format.
To include Apache Math library to your project, add the following dependency as per the build tool.
<!- - Maven - -> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-math3</artifactId> <version>3.6.1</version> </dependency> <!- - Gradle - -> compile group: 'org.apache.commons', name: 'commons-math3', version: '3.6.1'
Hope this article helped you in calculating the sum of all elements of an array in java.