Java Collectors.groupingBy 找不到错误

Java Collectors.groupingBy cant find error

编译器在这里给我一个非静态方法错误,我已经知道这并不意味着它一定是问题,但我真的找不到其他任何东西,特别是因为我在不同的地方有相同的方法class 只是为了传球,一切正常。

public Map<Integer, Map<Integer, Double>> setup(ArrayList<RunPlay> play){
Map<Integer, Map<Integer,Double>> map =
         plays.stream()
                    .collect(
                            Collectors.groupingBy(RunPlay::getYardline, Collectors.groupingBy(RunPlay::getDown, Collectors.averagingDouble(PassPlay::getPoints)))
                    );
    return map;

这是 RunPlay class:

public class RunPlay {

private int yardline;
private int down;
private int togo;
private int gained;
private int td;

public RunPlay(int yardline, int down, int togo, int gained, int td){

    this.down=down;
    this.gained=gained;
    this.td=td;
    this.togo=togo;
    this.yardline=yardline;

}

public double getPoints(){
    double result=0;
    result+=((getGained()*0.1)+(td*6));
    return result;
}

public int getYardline() {
    return yardline;
}

public int getGained() { return gained; }

public int getDown() { return down; }

public int getTd() {
    return td;
}

public int getTogo() {
    return togo;
}
}

您的 stream 管道的元素是 RunPlay 个实例。因此,当您调用 RunPlay::getYardline 时,会在传入的对象上调用相关方法,在您的情况下,该对象是 RunPlay 实例。但是如何调用 PassPlay::getPoints,这在使用方法引用的上下文中是不可能的。所以如果你需要这样做,你必须使用像这样的 lambda 表达式,假设该方法是一个实例方法,

Map<Integer, Map<Integer, Double>> map = plays.stream()
    .collect(Collectors.groupingBy(RunPlay::getYardline, Collectors.groupingBy(RunPlay::getDown,
        Collectors.averagingDouble(ignored -> new PassPlay().getPoints()))));

但是,您可以在此上下文中使用上面使用的相同方法引用,这是合法的。

Function<PassPlay, Double> toDoubleFn = PassPlay::getPoints;

因此 getPoints 方法将在传入的实例上调用。