Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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)));
like image 500
spacitron Avatar asked Mar 14 '23 13:03

spacitron


1 Answers

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.

like image 170
Tagir Valeev Avatar answered Mar 23 '23 23:03

Tagir Valeev