How to calculate average of an arraylist in java

What you will learn here about

  • How to calculate average of an array list in java

Here we will see How to calculate average of an array list in java. With the help of stream it is very easy to calculate average of an arraylist in java.

How to calculate average of an array list in java

Below sample program to calculate the average of an array list is given

import java.util.ArrayList;
import java.util.List;

public class Avg {
    public static void main(String[] args) {

        List numbers = new ArrayList<>();
        numbers.add(10);numbers.add(10);
        numbers.add(20);numbers.add(20);
        numbers.add(30);numbers.add(30);

        Double numbersAvg = numbers.stream().mapToDouble(Integer::intValue).average().getAsDouble();

        System.out.println("numbers Avg is  -> "+numbersAvg);
    }
}

OUTPUT

numbers Avg is -> 20.0

You may also like...