I think, this is only possible with an intermediate “pair” value to remember the association between a person/manager and the originating item. In absence of a standard pair type in Java’s standard API, we have to resort to Map.Entry
which comes closest to a Pair
type:
Map<Person, List<Item>> map = list.stream()
.flatMap(item->item.getOwners().stream()
.map(p->new AbstractMap.SimpleEntry<>(p.getManager(), item)))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
after improving it using import static
we get
Map<Person, List<Item>> map = list.stream()
.flatMap(item->item.getOwners().stream().map(p->new SimpleEntry<>(p.getManager(), item)))
.collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
It results in
m1: [i1,i3]
m3: [i1,i2]
m2: [i1,i2]
which differs because first, the standard map has no defined ordering, second, I think you made a mistake regarding you expectation as m1
is not associated with i2
in your example data.