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 * Arrays.stream()* 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};
//1
long sum = Arrays.stream(intArray).sum();
//2
long sum = Arrays.stream(integerArray).mapToInt(i -> i).sum();
//3
long sum = Arrays.stream(intArray).summaryStatistics().getSum();
```

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

```
long sum = 0;
for (int value : intArray) {
sum += value;
}
System.out.println(sum);
```

## 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*.

```
//1
double average = Arrays.stream(intArray).average().orElse(Double.NaN);
//2
double average = Arrays.stream(intArray).summaryStatistics().getAverage();
```

## 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 applying the filtering on the stream items without affecting the original array.

Happy Learning !!

## Leave a Reply