简体   繁体   English

Java collect函数给出了循环推理错误

[英]Java collect function gives cyclic inference error

When typing the following code I get a "cyclic inference" error on the argument for the groupingBy function: 键入以下代码时,我在groupingBy函数的参数上出现“循环推理”错误:

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

and neither does this: 这两个都没有:

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

The problem is that your resulting type is incorrect. 问题是您的结果类型不正确。 It should be Map<String, List<User>> : 它应该是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. 错误消息看起来令人困惑,但代码中确实存在错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM