How to calculate mean of a double array with Collectors.averagingDouble?

Viewed 284

I don't understand why the following code is not able to compile:

import java.util.Arrays;
import java.util.stream.Collectors;

public class AppMain {

    public static void main(String args[]) {

        double[] x = {5.4, 5.56, 1.0};
        double avg = Arrays.stream(x).collect(Collectors.averagingDouble(n -> n));
    }
}

The error message is totally unclear.

The method collect(Supplier<R>, ObjDoubleConsumer<R>, BiConsumer<R,R>) in the type DoubleStream is not applicable for the arguments (Collector<Object,?,Double>)
    Type mismatch: cannot convert from Collector<Object,capture#1-of ?,Double> to Supplier<R>
    Type mismatch: cannot convert from Object to double
1 Answers

Arrays.stream(x) for a double array returns a DoubleStream. The DoubleStream interface has different collect method than the Stream interface, and it doesn't accept a Collector.

You can simply use average() method of DoubleStream:

double avg = Arrays.stream(x).average().getAsDouble();

If you insist on using avergingDouble you'll need a Stream<Double>, which you can obtain by:

double[] x = {5.4, 5.56, 1.0};
double avg = Arrays.stream(x).boxed().collect(Collectors.averagingDouble(n -> n));

or by:

Double[] x = {5.4, 5.56, 1.0};
double avg = Arrays.stream(x).collect(Collectors.averagingDouble(n -> n));
Related