Languages
[Edit]
EN

Java - calculate average of ArrayList

0 points
Created by:
Kourtney-White
635

In this article, we would like to show you how to calculate the average of an ArrayList in Java.

Quick solution:

private static double average(List<Integer> numbers) {
    Integer sum = 0;
    if (!numbers.isEmpty()) {
        for (Integer number : numbers) {
            sum += number;
        }
        return sum.doubleValue() / numbers.size();
    }
    return 0;
}

 

1. Using enhanced for loop

In this example, we calculate the average of myArrayList.

To do so we take the following steps:

  • create an Integer variable to sum all the ArrayList elements,
  • use Integer.doubleValue() method to convert the number to a double,
  • divide the sum of all elements by the  ArrayList size.
import java.util.*;

public class Example {

    private static double average(List<Integer> numbers) {
        Integer sum = 0;
        if (!numbers.isEmpty()) {
            for (Integer number : numbers) {
                sum += number;
            }
            return sum.doubleValue() / numbers.size();
        }
        return 0;
    }

    public static void main(String[] args) {
        List<Integer> myArrayList = new ArrayList<>() {{
            add(2);
            add(4);
        }};

        System.out.println(average(myArrayList));  // 3.0
    }
}

Output:

3.0

2. Using Streams

In this example, we use streams to calculate the average value of myArrayList.

Note:

This solution works only for Java 8 and newer versions.

import java.util.*;

public class Example {

    private static double average(List<Integer> numbers) {
        return numbers.stream()
                .mapToDouble(d -> d)
                .average()
                .orElse(0.0);
    }

    public static void main(String[] args) {
        List<Integer> myArrayList = new ArrayList<>() {{
            add(2);
            add(4);
        }};

        System.out.println(average(myArrayList));  // 3.0
    }
}

Output:

3.0

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - ArrayList

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join