Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

IntStream.average()

Computes the arithmetic mean of the numbers in a stream.

Available since: Java 8

Syntax

OptionalDouble average()

Return value

OptionalDoubleThe mean, or an empty result for an empty stream.

Examples

The mean and handling an empty stream:

void main() {
    IO.println(IntStream.of(4, 5, 9).average().getAsDouble());
    IO.println(IntStream.empty().average().orElse(0));
    var stats = IntStream.of(4, 5, 9).summaryStatistics();
    IO.println(stats.getMin() + " " + stats.getMax() + " " + stats.getAverage());
}

Output:

6.0
0.0
4 9 6.0

Notes

The result is an OptionalDouble: an empty stream has no mean. If you need the minimum, maximum, sum and mean at once, call summaryStatistics() — the data is traversed only once.

See also

Related recipes

In the tutorial

  • Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.

Thanks for reading!

Donate to the site — we work hard for you.