I have a task: Given a list of users each one with some privileges, group users by privileges. I should use the stream API. This is the only code, which came to my mind:
public Map<Privilege, List<User>> groupByPrivileges(List<User> users) {
return users.stream().collect(groupingBy(User::getPrivileges));
}
As you can see in the return type of the method, I need to get a map with single Privilege objects as keys, but a User may appear multiple times, under different keys, if they have multiple privileges.
The main problem is that User::getPrivilege
s returns List<Privilege>
, and I know only how to process a single Privilege
.
Collectors.groupingBy
unless you have astatic
import. Fixing those two things makes it compile for me