简体   繁体   中英

How to convert Object list into a map of <String, List<String>>?

I have a list of users

Collection<User> userList = groupManager.getUserList(groupName);

Not knowing the Java-Streams API that well, I want to map them into a map as follows: the key would be the user key, and the value would be a list the User object's other properties.

Map<String, List<String>> userDsiplayData = userList.stream()
     .collect(Collectors.toMap(User::getKey, **.......**))

I tried to replace **..... ** with Arrays.asList(User::getUsername(), User::getDisplayName(), User::getEmail()) or similar constructs but I can't seem to get it to work.

Just use a lambda:

Map<String, List<String>> userDsiplayData = userList.stream()
     .collect(Collectors.toMap(User::getKey, 
         user -> List.of(user.getUsername(), user.getDisplayName(), user.getEmail()))

And by the way, your Arrays.asList(User::getUsername(), User::getDisplayName(), User::getEmail()) piece is wrong - you try to return a list of method handles, rather than a mapping function (besides the fact that it's not syntactically correct - parentheses do not belong there).

In your case the collect should be like this:

.collect(Collectors.toMap(
        User::getKey, 
        u -> Arrays.asList(u.getUsername(), u.getDisplayName(), u.getEmail())));

You can also create a custom method which return the expected List of fields in User class:

public class User {
    private String key;
    private String username;
    private String displayName;
    private String email;

    // getters setters

    public List<String> getUserInfo() {
        return Arrays.asList(username, displayName, email)));
    }
}

and then you can call it by using method reference like this:

.collect(Collectors.toMap(User::getKey, User::getUserInfo));

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