java - 无法确定 Collectors.groupingBy 的返回类型
问题描述
之前已经回答了类似的问题,但我仍然无法弄清楚我的分组和平均方法有什么问题。
我尝试了多种返回值组合,例如Map<Long, Double>
, Map<Long, List<Double>
, Map<Long, Map<Long, Double>>
,Map<Long, Map<Long, List<Double>>>
但没有一个可以修复 IntelliJ 向我抛出的错误:'Non-static method cannot be referenced from a static context'。此刻我觉得我只是在盲目地猜测。那么谁能给我一些关于如何确定正确返回类型的见解?谢谢!
方法:
public static <T> Map<Long, Double> findAverageInEpochGroup(List<Answer> values, ToIntFunction<? super T> fn) {
return values.stream()
.collect(Collectors.groupingBy(Answer::getCreation_date, Collectors.averagingInt(fn)));
}
答题类:
@Getter
@Setter
@Builder
public class Answer {
private int view_count;
private int answer_count;
private int score;
private long creation_date;
}
解决方案
我得到的编译器错误是不同的,关于方法调用如何collect
不适用于参数。
您的返回类型Map<Long, Double>
是正确的,但出了问题的是您的ToIntFunction<? super T>
. 当您将此方法设为通用时,您是在说调用者可以控制T
; 调用者可以提供类型参数,例如:
yourInstance.<FooBar>findAverageInEpochGroupOrig(answers, Answer::getAnswer_count);
但是,此方法不需要是通用的。只需对地图的值ToIntFunction<? super Answer>
进行操作即可。Answer
这编译:
public static Map<Long, Double> findAverageInEpochGroup(List<Answer> values, ToIntFunction<? super Answer> fn) {
return values.stream()
.collect(Collectors.groupingBy(Answer::getCreation_date, Collectors.averagingInt(fn)));
}
顺便说一句,正常的Java 命名约定指定您将以驼峰式命名您的变量,例如“viewCount”而不是“view_count”。这也会影响任何 getter 和 setter 方法。
推荐阅读
- c# - 我可以使用具体方法订阅通用 Action 吗?
- r - 如何预测 VAR 模型并将变量绘制为 Fable 包 (R) 中的扇形图
- qt-designer - PyQt6 中的 QtDesigner 在哪里?
- javascript - 无法从 NodeJS 的函数中为全局变量赋值
- excel - Excel如何使用条件格式制作棋盘格表格范围
- ios - 在容器视图中的表视图中仍然获得白色背景颜色
- javascript - react-router 组件渲染在 AWS s3 存储桶中不起作用
- javascript - 删除可拖动部分以在 JQUERY 中进行排序
- python - 帮助在准确的时间运行几行代码
- pandas - 熊猫将值从一列复制到另一列,如果一个存在而另一个是 NaN/Null