首页 > 解决方案 > 如何使用子列表作为键和父对象作为值来映射列表

问题描述

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

标签: javajava-stream

解决方案


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

推荐阅读