How do you find the sum of all the numbers in an array in Java?

TomLisankie picture TomLisankie · Dec 29, 2010 · Viewed 684.2k times · Source

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.

Answer

msayag picture msayag · Jul 25, 2013

In 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.*;