首页 > 解决方案 > Java Collectors.groupingBy 找不到错误

问题描述

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

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

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

标签: javajava-streamcollect

解决方案


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方法将在传入的实例上调用。


推荐阅读