Finding Sum and Average of Array Items

Learn to find the sum and average of the numbers stored in an array. We will be using the Java Stream API and simple for loop to find these values.

Note that the numbers in Java are represented with 8 primitives i.e. short, char, byte, boolean, int, float, long and double.

  • We can use IntStream for short, char, byte, boolean and int values.
  • We can use LongStream for long values.
  • We use DoubleStream for floating point numbers such as float and double.

When we pass the primitive arrays in the method then we get any one type of the stream i.e. IntStream, LongStream or DoubleStream.

The above information is necessary while getting the stream from an array, and using appropriate methods for calculating the aggregate values such as sum and average.

1. Finding Sum of Array Items

There are a couple of ways to get the sum of numbers stored in an array.

  • long Stream.sum()
  • long Stream.summaryStatistics().sum()
  • Iterating items using for loop.

Let us see the example of both methods using int[] and Integer[] array types. We will get the sum in either long or double data type based on the type of stream we are getting the array.

int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer[] integerArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

long sum =;

long sum =
        .mapToInt(i -> i)

long sum =

If we want to loop the item then it can be done as follows.

long sum = 0;

for (int value : intArray) {
  sum += value;


2. Finding Average of Array Items

Finding the average is pretty much similar to finding the sum as described in the previous section. We can call the stream.average() method in place of sum().

The data type used for storing the average is double.

double average =

double average =

3. Conclusion

In this short tutorial, we learned to use the stream API to get the sum and the average of the items stored in an array. Using the streams provides additional benefits such as we can apply the filtering on the stream items without affecting the original array.

Happy Learning !!

Sourcecode on Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.