Reputation: 2183
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)));
Upvotes: 4
Views: 2989
Reputation: 100149
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.
Upvotes: 7