1. Introduction

In this quick tutorial, we’ll cover how we can calculate sum & average in an array using both Java standard loops and the Stream API.

2. Find Sum of Array Elements

2.1. Sum Using a For Loop

In order to find the sum of all elements in an array, we can simply iterate the array and add each element to a sum accumulating variable.

This very simply starts with a sum of 0 and add each item in the array as we go:

public static int findSumWithoutUsingStream(int[] array) {
    int sum = 0;
    for (int value : array) {
        sum += value;
    }
    return sum;
}

2.2. Sum With the Java Stream API

We can use the Stream API to achieve the same result:

public static int findSumUsingStream(int[] array) {
    return Arrays.stream(array).sum();
}

It’s important to know that the sum() method only supports primitive type streams.

If we want to use a stream on a boxed Integer value, we must first convert the stream into IntStream using the mapToInt method.

After that, we can apply the sum() method to our newly converted IntStream:

public static int findSumUsingStream(Integer[] array) {
    return Arrays.stream(array)
      .mapToInt(Integer::intValue)
      .sum();
}

You can read a lot more about the Stream API here.

3. Find Average in a Java Array

3.1. Average Without the Stream API

Once we know how to calculate the sum of array elements, finding average is pretty easy – as Average = Sum of Elements / Number of Elements:

public static double findAverageWithoutUsingStream(int[] array) {
    int sum = findSumWithoutUsingStream(array);
    return (double) sum / array.length;
}

Notes:

  1. Dividing an int by another int returns an int result. To get an accurate average, we first cast sum to double.
  2. Java Array has a length field which stores the number of elements in the array.

3.2. Average Using the Java Stream API

public static double findAverageUsingStream(int[] array) {
    return Arrays.stream(array).average().orElse(Double.NaN);
}

IntStream.average() returns an OptionalDouble which may not contain a value and which needs a special handling.

Read more about Optionals in this article and about the OptionalDouble class in the Java 8 Documentation.

4. How to Calculate the Average of a 2D Array in Java

Calculating the average of a 2D array follows a similar logic as with a 1D array. We need to sum all the elements and then divide by the total number of elements.

4.1. Average Without the Stream API

First, the average can be calculated using nested loops. Let’s consider the following method:

The findAverageWithoutUsingStream() method determines the average of a 2D array using two nested loops. Initially, two variables, sum and count, are set to zero. The outer loop iterates through each array row, and the inner loop goes through each element within these rows. Each element’s value is added to sum, and count is incremented accordingly.

Once all elements have been processed, the average is obtained by dividing sum by count. Casting sum to double ensures precise division and results in a double value.

4.2. Average Using the Java Stream API

Alternatively, the average can be calculated using the Stream API. Here is how it can be done:

public static OptionalDouble findAverageUsingStream(int[][] array) {
    return Arrays.stream(array)
      .flatMapToInt(Arrays::stream)
      .average();
}

The findAverageUsingStream() method calculates the average of a 2D array using the Stream API. This process starts by converting the 2D array into a stream of 1D arrays with Arrays.stream(array). The stream of 1D arrays is then flattened into a single IntStream using flatMapToInt(Arrays::stream). This IntStream contains all the elements of the 2D array in a single stream. The average is then calculated using the average() method of the IntStream, which returns an OptionalDouble.

5. Conclusion

In this article, we explored how to find sum/average of int array elements.

As always, the code is available over on Github.