This post will discuss how to calculate the arithmetic mean (average) of all items in a List in Java.

1. Using Stream.average() method

If you use JDK version 1.8 or above, you might want to use Stream for this trivial task. The idea is to convert the List into the corresponding primitive stream i.e, IntStream, DoubleStream, or LongStream, and call the average() method on it. It returns an optional describing the average of elements in the stream, or an empty optional if the stream is empty. Here’s the complete code:

Download  Run Code

2. Using SummaryStatistics

Another plausible way in Java 8 is to get SummaryStatistics of the corresponding primitive stream, which provides statistics such as count, min, max, sum, and average about the elements of the stream.

The following example demonstrates its usage to obtain the arithmetic mean of elements of the stream:

Download  Run Code

 
Here’s equivalent code without converting the list to a primitive stream.

Download  Run Code

3. Using Guava

If you prefer the Guava library, you can use Stats class which is a bundle of statistical summary values like sum, count, mean, min, and max, etc. To calculate the arithmetic mean of the list, you can use the static Stats.meanOf() method.

Download Code

4. Using for loop

If you’re on older versions of Java (Java 7 and before) and don’t prefer third-party libraries, you can write your custom routine for this simple task using a simple for-loop:

Download  Run Code

That’s all about calculating the average of all items in a List in Java.