[Java] How to find sum of all elements of an array?


I want to compute sum of all elements of an array, how can I do that in Java?

1 Answer

3 years ago by

Using reduce on stream we can calculate sum of all elements in an array. Following code shows how to do that.

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		int[] array = { 1, 45, 34, 2 };
		int sum = Arrays.stream(array).reduce(0, (a, b) -> a + b);
		System.out.println(sum);
	}
}

Output:

82

Try this code online here https://onecompiler.com/java/3xmt8reyf

3 years ago by Karthik Divi