2017-11-06 19 views
3

次のコードはコンパイルできない理由を私は理解していない:Collectors.averagingDoubleで二重配列の平均を計算するには?

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 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 

答えて

4

Arrays.stream(x)doubleアレイのDoubleStreamを返します。 DoubleStreamインターフェイスは、Streamインターフェイスとは異なるcollectメソッドを持ち、Collectorを受け入れません。

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

かによって:

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

あなたはavergingDoubleを使う、という場合は、あなたがすることによって得ることができStream<Double>を、必要があります

あなたは、単にDoubleStreamaverage()方法を使用することができます

Double[] x = {5.4, 5.56, 1.0}; 
double avg = Arrays.stream(x).collect(Collectors.averagingDouble(n -> n)); 
関連する問題