How can I transform a collection into a Guava Multimap grouped by the elements of a nested collection property?

前端 未结 4 1224
广开言路
广开言路 2020-12-14 21:28

I have a List and want a Guava Multimap where we\'ve grouped the Foos by each tag of their Collection

4条回答
  •  -上瘾入骨i
    2020-12-14 22:01

    You can use Stream.flatMap to create a stream on each tag/foo pair, and then collect it into a multimap. Newer versions of Guava provide collectors such as ImmutableSetMultimap.toImmutableSetMultimap and ImmutableListMultimap.toImmutableListMultimap for this purpose.

    ImmutableSetMultimap result = list.stream()
            .flatMap(foo -> foo.getTags().stream().map(tag -> Map.entry(tag, foo)))
            .collect(ImmutableSetMultimap.toImmutableSetMultimap(Map.Entry::getKey, Map.Entry::getValue));
    

提交回复
热议问题