[英]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.不知道 Java-Streams API 好,我想将 map 转换为 map,如下所示:密钥将是用户密钥,值将是用户对象的其他属性列表。
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.我试图用
Arrays.asList(User::getUsername(), User::getDisplayName(), User::getEmail())
或类似的结构替换 **..... ** 但我似乎无法得到它工作。
Just use a lambda:只需使用 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).顺便说一句,您的
Arrays.asList(User::getUsername(), User::getDisplayName(), User::getEmail())
部分是错误的 - 您尝试返回方法句柄列表,而不是映射 function (除了它在语法上不正确的事实 - 括号不属于那里)。
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:您还可以创建一个自定义方法,该方法返回用户 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.