Home Communities
IT Knowledge
Inspiration
Languages
EN

# Java - calculate average of ArrayList

0 points
Created by:
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<>() {{
}};

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<>() {{
}};

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

Output:

``3.0``

## References

Join to our subscribers to be up to date with content, news and offers.