Java 8- Find the Average of List of Integers


In Java 8, the average() method of the DoubleStream interface calculate the average of the list of integers.

1. Stream API

double avg = numbers.stream().mapToDouble(num -> num).average().getAsDouble();

2. Old Style

double sum = 0.0;
for (Integer num : numbers) {
	sum += num;
}
double avg2 = sum / numbers.size();

Check the complete example.

CalculateAvg.java
package org.websparrow;

import java.util.Arrays;
import java.util.List;

/**
 * @author Atul Rai
 */
public class CalculateAvg {

	public static void main(String[] args) {

		List<Integer> numbers = Arrays.asList(10, 5, 15, 7, 12, 3, 31);

		// 1. Java 8 stream
		byStreamAPI(numbers);

		// 2. Old style
		byOldStyle(numbers);

	}

	private static void byStreamAPI(final List<Integer> numbers) {

		double avg = numbers.stream().mapToDouble(num -> num).average().getAsDouble();

		System.out.println("Average by Stream API= " + avg);
	}

	private static void byOldStyle(final List<Integer> numbers) {

		double sum = 0.0;
		for (Integer num : numbers) {
			sum += num;
		}

		double avg2 = sum / numbers.size();
		System.out.println("Average by old style= " + avg2);
	}
}
console
Average by Stream API= 11.857142857142858
Average by old style= 11.857142857142858

References

  1. Java- Find the element in the List having maximum value
  2. Different ways to iterate/loop a List of Integers in Java
  3. Java 8 Stream- Sum of List of Integers

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.