Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

sum

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.

like image 640
TomLisankie Avatar asked Dec 29 '10 00:12

TomLisankie


People also ask

Which function finds sum of all the values in an array?

You can also use Python's sum() function to find the sum of all elements in an array.


2 Answers

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.*; 
like image 126
msayag Avatar answered Sep 22 '22 02:09

msayag


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(); 
like image 42
Alexis C. Avatar answered Sep 24 '22 02:09

Alexis C.