Java collect function gives cyclic inference error

人盡茶涼 提交于 2019-12-07 11:04:00

问题


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

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

回答1:


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.



来源:https://stackoverflow.com/questions/33034307/java-collect-function-gives-cyclic-inference-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!