简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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