无法找出 return 类型的 Collectors.groupingBy

Cannot figure out return type of Collectors.groupingBy

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

我尝试了多个 return 值组合,例如 Map<Long, Double>Map<Long, List<Double>Map<Long, Map<Long, Double>>Map<Long, Map<Long, List<Double>>> 和 none错误 IntelliJ 向我抛出:'Non-static method cannot be referenced from a static context'。 此刻我觉得我只是在盲目猜测。那么谁能给我一些关于如何确定正确的 return 类型的见解?谢谢!

方法:

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

回答class:

@Getter
@Setter
@Builder
public class Answer {
    private int view_count;
    private int answer_count;
    private int score;
    private long creation_date;
}

我得到的编译器错误是不同的,关于如何调用 collect 的方法不适用于参数。

你的 return 类型的 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 方法。