# Java Calculate Average of List

In Java, List is a linear data structure that store the ordered collection of data. It also accepts the duplicate values but preserve the insertion order. Sometimes, it is required to find the minimum and maximum element of the list, sum, and average of the list, etc. In this section, we will calculate the average of List using Java for loop, Java 8 Stream, and IntSummaryStatistics class.

## Java Programs to Calculate the Average of List

### Using Java for Loop

The logic is very simple. First, we will initialize a variable sum to 0 that holds the sum of the list elements. Declare another element say average (avg), it holds the average of the list.

We have created an instance of the ArrayList class and invoked the add() method to add the elements to the List. A for loop iterate over the list and get an element at each iteration and add that element to the variable sum.

After that, we have calculated the average of the list, dividing the sum by the size of the list (number of elements).

Let's implement the above approach in a Java program.

AverageOfList.java

Output:

```The average of the List: 33
```

Let's see another logic for the same.

FindAverageOfList.java

Output:

```The average of the List is: 55.0
```

## Using IntSummaryStatistics Class

IntSummaryStatistics is a class that belongs to java.util package. It implements the IntStream class. The class is dedicated to work with streams. A state object for collecting statistics such as count, min, max, sum, and average. In the following Java programs, we have used the following methods:

• stream(): The method returns a sequential Streamwith this collection as its source.
• mapToInt(): It is a lazy intermediate operation. The operations are invoked on a Stream instance and once the operation finish their processing, they give a Stream instance as output.
• summaryStatistics(): The method returns an IntSummaryStatistics describing various summary data about the elements of this stream like count of number of elements in the IntStream, average of all elements present in IntStream, minimum and maximum element in the IntStream and so on. It is a terminal operation. It means, it may traverse the stream to produce a result.
• getAverage(): The method returns the arithmetic mean of values recorded, or zero if no values have been recorded.

CalculateAverageOfList.java

Output:

```The average of the List is: 58.166666666666664
```