java - 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;
}
}
解决方案
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
方法将在传入的实例上调用。
推荐阅读
- apache-kafka-streams - Kafka 流 - 尝试从流中过滤数据并写入另一个主题。但返回空
- vue.js - 使用 v-bind:href 绑定表达式
- machine-learning - 向前向后隐藏马尔可夫模型和左右隐藏马尔可夫模型之间有什么区别吗?
- c# - 在 .NET Core 3 中记录请求负载
- r - 我可以使用 DESeq2 的结果子集来计算 Bray-Curtis 相异度,然后绘制 PCoA 吗?
- javascript - 我正在尝试在单击时从 redux 存储加载数据并更新状态,但是状态中的数据在单击时没有得到更新
- c++ - Why is glCheckFramebufferStatus always 36054 for GL_DEPTH_COMPONENT on OpenGL ES 3.1+?
- android - Jetpack compose 中带有提示文本的 TextField
- performance - 查询仅返回我表的 12 个值中的 4 个。为什么会这样?
- mysql - 如何在复合键是访问号码和日期 +/- 1 天的情况下进行表连接