簡體   English   中英

Java Collectors.groupingBy找不到錯誤

[英]Java Collectors.groupingBy cant find error

編譯器在這里給了我一個非靜態方法錯誤,我已經知道這並不意味着一定是問題,但是我真的找不到其他任何東西,尤其是因為我在不同的類中有相同的方法只是為了傳球一切正常。

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

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方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM