Java collect函数给出了循环推理错误 [英] Java collect function gives cyclic inference error
问题描述
当键入以下代码时,我在groupingBy函数的参数上得到循环推理错误:
When typing the following code I get a "cyclic inference" error on the argument for the groupingBy function:
Map<String, User> mapByEmail = users.stream().collect(Collectors.groupingBy(User::getEmail));
我发现这令人困惑,因为以下不会导致任何问题:
I find this confusing because the following does not cause any problem:
users.stream().collect(Collectors.groupingBy(User::getEmail));
且这两者都不是:
List<User> listByEmail = users.stream().collect(Collectors.groupingBy(User::getEmail)).values().stream().reduce(null, (a,b)-> a=b);
所以问题是,什么是循环推理,我该如何避免呢?
So the question is, what is a cyclic inference and how can I avoid it?
编辑感谢您的回答。经过进一步研究后,我发现需要通过以下方式减少我的结果:
EDIT Thanks for the answers. After further research I found out that I need to reduce my result by doing the following:
Map<String, User> mapByEmail = users.stream().collect(Collectors.groupingBy(User::getEmail, Collectors.reducing(new User(),(a,b)-> a=b)));
推荐答案
问题是结果类型不正确。它应该是 Map< String,List< User>>
:
The problem is that your resulting type is incorrect. It should be Map<String, List<User>>
:
Map<String, List<User>> mapByEmail = users.stream()
.collect(Collectors.groupingBy(User::getEmail));
错误消息看起来令人困惑,但代码中确实存在错误。
The error message looks confusing, but there's actual an error in your code.
这篇关于Java collect函数给出了循环推理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!