In this article, we’ll learn to find the sum and average of all elements in a given Java array. We’ll first cover the basic for loop-based approach and then extend our knowledge to achieve the same using Java Streams API.
Let’s look at how we can find the sum total of all elements in a Java array:
A pretty intuitive way to achieve it is to use a for-loop. The idea to keep on adding all elements till we reach the end of an array:
int getSumOfArray(int[] numbers) { int sum = 0; for(int c = 0; c < numbers.length; c++) sum += numbers[c]; return sum; }
A more readable way to achieve it would be to use an extended – for loop instead:
int getSumOfArray(int[] numbers) { int sum = 0; for(int element : numbers) sum += element; return sum; }
We can also choose to use Streams API to find the sum:
int numbers[] = {2, 3, 1, 5, 4}; int sum = Arrays.stream(numbers) .sum();
java.util.stream.IntStream is the int primitive-type specialization of a stream which exposes sum(), average() and other similar operations.
Finding an average of elements in a Java array could be achieved using:
As we all know, the mathematical definition of average itself is:
average = sum / count;
where,
the sum is the sum of all elements in the array
And the count is the total number of elements in an array
So, our code would look like:
double average = (double) getSumOfArray(numbers) / numbers.length;
Note that we first cast the sum to a double value to ensure we get an accurate average value.
Intstream also provides an average() method to help us find an average:
double avg = Arrays.stream(array) .average() .orElse(Double.NaN);
average() method in IntStream class returns an OptionalDouble.
Here, we are returning a Double.NaN value in case the Optional is found empty.
In this article, we explored ways to find the sum and average of elements in a Java array.