Concept: two types A
and B
, each may map to multiple elements of the other type.
Suppose I have an input list: List<A> aList
, how to generate a map Map<B, List<A>> result
with Java 8 stream?
Map<B, List<A>> result = aList.stream().flatMap(a -> a.getBs().stream().map(b -> new Tuple2<>(b, a)) // just create pairs of (B, A) for each a
.collect(Collectors.groupingBy(???)); // then group these pairs by b
Or would Guava or Apache Comms provide such functionality?
Thanks!
UPDATE:
Thanks to @Tukani, please look at this post for answer.