0

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.

Community
  • 1
  • 1
CloudyTrees
  • 711
  • 2
  • 10
  • 20
  • 2
    Can you post your Tuple2 class? As a hint, you need to group by the first field of your tuple, and as downstream, map the tuple to its second field and collect it into a list. See http://stackoverflow.com/questions/38471056/java8-streams-transpose-map-with-values-as-list/ – Tunaki Aug 06 '16 at 19:52
  • Thanks @Tunaki, that worked for me! – CloudyTrees Aug 07 '16 at 03:38

0 Answers0