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.0Notes
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
- IntStream.sum() — Adds up all numbers of a stream.
- Collectors.averagingDouble() — A collector that computes the mean of a numeric field.
- Stream.mapToInt() — Turns a stream of objects into a stream of `int` numbers.
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.