首页 > 解决方案 > 无法确定 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;
}

标签: javajava-streamcollectors

解决方案


我得到的编译器错误是不同的,关于方法调用如何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 方法。


推荐阅读