简体   繁体   中英

Using groupBy to transform list to map

Lets say I have a list of objects that look like this:

Foo
int id
Owner owner
int targetId

I would like to transform this list into a mapping of Map<Owner, Set<Integer>> ownerToTargetIds which will have a key for each unique owner found in the list of Foo objects and have a value for all the targetIds found in each foo object for that owner. Ex:

Foo a {1, 2, 3}
Foo b {2, 2, 4}
Foo c {3, 2, 5}

In the above you would transoform this list to a Map with key = 2, values = Set{3,4,5}.

I have tried to use the grouping functionality in streams to get to the point where I can get a mapping from owner to the entire record but that doesnt really work:

Map<Owner, List<Foo>> userToTargetIds = foo.get().stream()
                    .collect(toMap(Foo::getTargetId));

As JB Nizet said: RTM

but here the snipped:

Map<Owner, Set<Integer>> userToTargetIds
         = fooList.stream().collect(groupingBy(Foo::getOwner,
                                              mapping(Foo::getTargetId, toSet())));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM