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.
The average of the List: 33
Let's see another logic for the same.
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:
The average of the List is: 58.166666666666664