Average value of an ArrayList in Java

Hi coders! I am up with a topic known as ArrayList. It is a class which implements List interface of the Collection framework. ArrayList is present in the java package known as util. It is very useful since it provides dynamic arrays and allows lots of manipulations. Let’s learn how to find the average value of ArrayList elements in Java.

ArrayList cannot be used for primitive datatypes like int, float, char etc, It uses objects but it can use these primitive datatypes with the help of wrapper class in java.

In ArrayList, addition of the elements does not maintain the same sequence they may array in any order. Suppose you may add [10, 20, 30, 40, 50]. so it is not necessary that it will be in the same sequence when you will print the List you may see the output such as [30, 20, 10, 50, 40] or in any sequence.

ArrayList has various constructors:

  1. ArrayList(): Creates an empty ArrayList.
  2. ArrayList(Collection c): Creates an ArrayList, initialized with the elements in it.
  3. ArrayList(int capacity): Use to build an ArrayList with initial capacity being specified.

ArrayList provides a lot of function set for various purposes. Now if we have to find the average of an ArrayList then what will be the approach?

Suppose an ArrayList [10,15, 20, 25, 30], to find the average value of this array list see the code. To know the solution understands the code carefully.

Code for the calculation of average value of ArrayList elements in Java

import java.util.ArrayList;   /* ArrayList class importing from util package */

public class ExampleList {
   // driver function
  public static void main(String[] args) {
    ArrayList<Integer> li = new ArrayList<Integer>();  /*Integer arrayList*/
                 /* adding elements to the arrayList */
    li.add(10);
    li.add(15);
    li.add(20);
    li.add(25);
    li.add(30);
    int total = 0;
    int avg;
    for(int i = 0; i < li.size(); i++)
    
        total += li.get(i);
        avg = total / li.size(); // finding ther average value
        System.out.println("The Average is: " + avg);
    

  }

}
// code is provided by Anubhav Srivastava
Output:

The average is: 20 

The time complexity of the solution is O(n)

If you are using Array instead of ArrayList then you can easily Convert list to int array in Java or Convert An ArrayList to Array In Java

Leave a Reply

Your email address will not be published. Required fields are marked *