1

I have to write a method which takes a List<User> and returns a Map<Role,List<User>>.

User contains a Person instance, which contains a Role.
I must create a map where Role key is mapped to a list of users (where user has this Role).

I tried the following :

public static Map<Role, List<User>> groupUsersByRole(List<User> users) {
    users.stream().collect(Collectors.toMap((u -> u.getPersonDetails().getRole()), users.stream().collect(Collectors.toList()  ) )
    users.stream().map(user -> user).filter(u -> u.).collect(Collectors.toList()) );
    //users.stream().filter(u -> u.getPersonDetails().getRole().getName().equals(u.getPersonDetails().getRole().getName())).map(user -> user.getName()).
    return null;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
virnik
  • 37
  • 1
  • 4

1 Answers1

0

What you are looking for is a Collectors.groupingBy, which groups the elements of the Stream by a specified property :

Map<Role, List<User>> map = users.stream().collect(Collectors.groupingBy(u->u.getPersonDetails().getRole()));
Eran
  • 387,369
  • 54
  • 702
  • 768