2

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.

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

With Java 9 or higher, you can also use List.of(...) instead of Arrays.asList(..), with the added benefit that the list is immutable (instead of only fixed size).
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.