I'm having a problem finding the sum of all of the integers in an array in Java. I cannot find any useful method in the Math
class for this.
You can also use Python's sum() function to find the sum of all elements in an array.
In java-8 you can use streams:
int[] a = {10,20,30,40,50}; int sum = IntStream.of(a).sum(); System.out.println("The sum is " + sum);
Output:
The sum is 150.
It's in the package java.util.stream
import java.util.stream.*;
If you're using Java 8, the Arrays
class provides a stream(int[] array)
method which returns a sequential IntStream
with the specified int
array. It has also been overloaded for double
and long
arrays.
int [] arr = {1,2,3,4}; int sum = Arrays.stream(arr).sum(); //prints 10
It also provides a method stream(int[] array, int startInclusive, int endExclusive)
which permits you to take a specified range of the array (which can be useful) :
int sum = Arrays.stream(new int []{1,2,3,4}, 0, 2).sum(); //prints 3
Finally, it can take an array of type T
. So you can per example have a String
which contains numbers as an input and if you want to sum them just do :
int sum = Arrays.stream("1 2 3 4".split("\\s+")).mapToInt(Integer::parseInt).sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With