Search code examples
javacollectors

How to create a map that takes values from other map and then maps them to its field?


So I have a map of ids to systemUsers and now I want to create a map of systemUser keys and login values. Login is a field inside systemUser class. I have a problem with how to write the mapper functions or even if it's the right way to go about it

Map<Long, PHSystemUser> systemUserMap = getPersistenceLogic()
                      .getSystemUsersMap(serviceClientMap.values());

Map<PHSystemUser, String> loginMap = systemUserMap.values().stream()
                      .map(PHSystemUser::getLogin)
                      .collect(Collectors.toMap(, ));

Solution

  • All you need is to collect directly using two functions:

    systemUserMap.values().stream()
       .collect(Collectors.toMap(Function.identity(), PHSystemUser::getLogin));
    

    The problem with .map(PHSystemUser::getLogin) is that it changes the stream to Stream<String>, leaving you no chance to have the entire PHSystemUser object downstream.