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

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


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


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();


This is one of those simple things that doesn't (AFAIK) exist in the standard Java API. It's easy enough to write your own.

Other answers are perfectly fine, but here's one with some for-each syntactic sugar.

int someArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};int sum = 0;for (int i : someArray)    sum += i;

Also, an example of array summation is even shown in the Java 7 Language Specification. The example is from Section 10.4 - Array Access.

class Gauss {    public static void main(String[] args) {        int[] ia = new int[101];        for (int i = 0; i < ia.length; i++) ia[i] = i;        int sum = 0;        for (int e : ia) sum += e;        System.out.println(sum);    }}