无法找出Collectors.groupinBy的返回类型

sjn*_*jne 1 java java-stream collectors

之前已经回答过类似的问题,但是我仍然无法弄清楚我的分组和平均方法有什么问题。

我曾尝试多个返回值的组合一样Map<Long, Double>Map<Long, List<Double>Map<Long, Map<Long, Double>>Map<Long, Map<Long, List<Double>>>和那些没有修复错误的IntelliJ我抛出的:“非静态方法不能从静态上下文中引用”。此刻,我觉得我只是在盲目猜测。那么,谁能给我一些关于如何确定正确的回报类型的见解?谢谢!

方法:

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)));
}
Run Code Online (Sandbox Code Playgroud)

答案类别:

@Getter
@Setter
@Builder
public class Answer {
    private int view_count;
    private int answer_count;
    private int score;
    private long creation_date;
}
Run Code Online (Sandbox Code Playgroud)

rge*_*man 5

我得到的编译器错误有所不同,关于方法调用的方式collect不适用于参数。

您的返回类型Map<Long, Double>是正确的,但出问题的是您的ToIntFunction<? super T>。当您使此方法通用时,就是说调用方可以控制T; 调用者可以提供类型参数,例如:

yourInstance.<FooBar>findAverageInEpochGroupOrig(answers, Answer::getAnswer_count);
Run Code Online (Sandbox Code Playgroud)

但是,此方法不需要通用。只需输入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)));
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,常规的Java命名约定指定您以驼峰形式命名变量,例如“ viewCount”而不是“ view_count”。这也会影响任何getter和setter方法。