java

How to calculate the average of an ArrayList in Java

In this tutorial, we are going to see how to calculate the average of a list in Java, using the ArrayList class. It is a class that implements the List interface of the Collection framework. ArrayList is present in the java package called util. It is very useful because it provides dynamic arrays and allows many manipulations. Let’s take a look at how to find the average value of the elements of an ArrayList in Java.

Suppose we have the following list [1, 2, 3, 4, 5], to find the average value of this list, see the following code.
 

Java Program to calculate the average of an ArrayList:
import java.util.*;   

public class Main {
  public static void main(String[] args) {
	  
    int sum = 0, avg;
    
    ArrayList<Integer> list = new ArrayList<Integer>();  
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4);
    list.add(5);

    for(int i = 0; i < list.size(); i++)
        sum += list.get(i);
    
    // find the average value
    avg = sum / list.size(); 
    System.out.println("The average is: " + avg);
  }
}

Output:

The average is: 3
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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