Collectors.averagingDouble()
A collector that computes the mean of a numeric field.
Available since: Java 8
Syntax
static <T> Collector<T, ?, Double> averagingDouble(ToDoubleFunction<? super T> mapper)Parameters
| Parameter | Type | Description |
|---|---|---|
| mapper | ToDoubleFunction<? super T> | Extracts a number from an element. |
Return value
Collector<T, ?, Double>An average collector.
Examples
The average grade per subject:
record Grade(String subject, double value) {}
void main() {
var grades = List.of(new Grade("math", 4), new Grade("art", 5),
new Grade("math", 5), new Grade("art", 3));
Map<String, Double> avg = grades.stream()
.collect(Collectors.groupingBy(Grade::subject, TreeMap::new,
Collectors.averagingDouble(Grade::value)));
IO.println(avg);
}Output:
{art=4.0, math=4.5}Notes
For an empty stream it returns 0.0 rather than an empty result. There are also averagingInt() and averagingLong() — both return a Double too.
See also
- Collectors.summingInt() — A collector that sums a numeric field of the elements.
- IntStream.average() — Computes the arithmetic mean of the numbers in a stream.
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
Related recipes
In the tutorial
- Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.