【问题标题】:Java Collectors.groupingBy cant find errorJava Collectors.groupingBy 找不到错误
【发布时间】:2018-10-12 20:16:02
【问题描述】:

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

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

【问题讨论】:

    标签: java java-stream collect


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-05-20
      • 2013-12-06
      • 2016-07-22
      • 2013-11-22
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      相关资源
      最近更新 更多