Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
mapperToDoubleFunction<? 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

Related recipes

In the tutorial

  • Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.

Thanks for reading!

Donate to the site — we work hard for you.