【问题标题】:Cannot figure out return type of Collectors.groupingBy无法确定 Collectors.groupingBy 的返回类型
【发布时间】:2019-07-09 20:20:24
【问题描述】:

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

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

【问题讨论】:

    标签: java java-stream collectors


    【解决方案1】:

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

    您的Map&lt;Long, Double&gt; 返回类型是正确的,但出错的是您的ToIntFunction&lt;? super T&gt;。当您将此方法设为通用时,您是在说调用者可以控制T;调用者可以提供类型参数,例如:

    yourInstance.<FooBar>findAverageInEpochGroupOrig(answers, Answer::getAnswer_count);
    

    但是,此方法不需要是通用的。只需输入ToIntFunction&lt;? super Answer&gt; 即可在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 方法。

    【讨论】:

    • 非常感谢!将界限从 T 更改为 Answer 有帮助!虽然我仍然不太明白出了什么问题。它与不兼容的界限有关吗?字段名称打破了约定,因为我使用它们将 JSON 映射到 Spring REST 使用者的 POJO。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多