EN
Java - calculate average of ArrayList
0
points
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 adouble
, - 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