In this tutorial, you will learn how to calculate average of a List in Java. This can be done on ArrayList of numbers such as list of Integer, Double, Float, Long type etc. There are several ways to do this, in this guide, we will see following two approaches:
- Using For loop
- Using Java Streams
1. Using For-Loop
In this example, we have an ArrayList of Integer type, and we are using for loop to calculate the average of ArrayList.
import java.util.ArrayList;
public class AverageCalculator {
public static void main(String[] args) {
// Creating an ArrayList of Integer type
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
// Calling user defined method to calculate the average
double average = calculateAverage(numbers);
// Print the average
System.out.println("The average is: " + average);
}
public static double calculateAverage(ArrayList<Integer> list) {
// If list is null or empty return 0
if (list == null || list.isEmpty()) {
return 0;
}
// else iterate the list using for loop
// and add each element to variable sum
double sum = 0;
for (int number : list) {
sum += number;
}
// Divide sum of elements by number of elements
// to calculate the average of ArrayList
return sum / list.size();
}
}
2. Using Java Streams (Java 8 and Later)
Java 8 introduced the Stream API, which can be used for this purpose. To learn more about Streams, refer Java Streams Tutorial.
import java.util.ArrayList;
import java.util.List;
public class AverageCalculator {
public static void main(String[] args) {
// Creating an ArrayList of Integer type
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
// Calculate the average using streams
double average = calculateAverage(numbers);
// Print the average
System.out.println("The average is: " + average);
}
// In this method, we are converting list to stream using stream()
// method then converting elements from Integer to int using mapToInt()
// and finally calling average() method to calculate the average of elements
public static double calculateAverage(List<Integer> list) {
return list.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
}
}
Leave a Reply