Core Java

Find Sum/Average In Java Array

Introduction:

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.

Finding Sum of Elements In Array:

Let’s look at how we can find the sum total of all elements in a Java array:

Approach 1:: Using Loop

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:

A more readable way to achieve it would be to use an extended – for loop instead:

 

Approach 2:: Using Java 8 Streams API

We can also choose to use Streams API to find the sum:

java.util.stream.IntStream is the int primitive-type specialization of a stream which exposes sum(), average() and other similar operations.

Finding Average Of Elements In Array:

Finding an average of elements in a Java array could be achieved using:

 

Approach 1:: Average = Sum/Total Count

As we all know, the mathematical definition of average itself is:

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:

Note that we first cast the sum to a double value to ensure we get an accurate average value.

 

Approach 2:: Java 8 Streams API

Intstream also provides an average() method to help us find an average:

average() method in IntStream class returns an OptionalDouble.

Here, we are returning a Double.NaN value in case the Optional is found empty.

 

Conclusion:

In this article, we explored ways to find the sum and average of elements in a Java array.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *