无法确定 Collectors.groupingBy 的返回类型



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

我已经尝试了多个返回值组合,如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)));
}

答案类:

@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"。 这也会影响任何吸气剂和二传手方法。

最新更新