java - 如何使用子列表作为键和父对象作为值来映射列表
问题描述
public class User {
private String userId;
private String role;
private List<String> privileges;
}
给定List<User> users
我如何Map<String, List<User>>
从用户那里获得每个权限的关键?
此代码生成 Map<List, List> 而不是预期的单个字符串键
users.stream().collect(Collectors
.groupingBy(User::getPrivileges, HashMap::new, Collectors.mapping(v -> v, Collectors.toList())));
如果我做一个平面图,就没有办法引用父对象
users.stream()
.flatMap(User::getPrivileges)
.collect(Collectors
.groupingBy(v->v, HashMap::new, Collectors.mapping(???, Collectors.toList())));
解决方案
You need to create a temporary pair that holds both the privilege (after flattening the list) and the related user, which you can then use in a grouping collector:
Map<String, List<User>> result = users.stream()
.flatMap(user -> user.getPrivileges()
.stream()
.map(priv -> new SimpleEntry<>(priv, user)))
.collect(
Collectors.groupingBy(Entry::getKey,
Collectors.mapping(Entry::getValue, Collectors.toList())));
推荐阅读
- c# - Mapster.Tool 使用 codegen 生成映射器而不是 DTO
- reactjs - react js create-react-app中的“未定义useHistory”
- python-3.x - Ray 没有将远程功能分发到本地机器上的所有节点
- javascript - Lodash 从嵌套数组中删除重复项
- javascript - 错误:必须使用“allowedNonPeerDependencies”选项明确允许依赖关系@types/html2canvas
- microsoft-dynamics - 在 Cloud Elements 中创建 MS 动态实例时无法交换代码以获得访问令牌错误
- html - 浮动效果 - 我的代码存在问题
- rust - 如何在 WASI 中使用 Rust 的 async/await 语法
- python - Python Selenuim,在没有 XPATH 的情况下找到具有特定属性的按钮
- javascript - 如何使用颤振/飞镖在解析(Back4App)中获取关系数据?