Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

java - How to map a list using sublist as key and parent object as value


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...