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

前端 未结 4 1225
广开言路
广开言路 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条回答
  • 2020-12-14 21:41

    This is slightly more idiomatic for Java 8 streams:

        Multimap<String, Foo> map = list.stream()
                //First build a stream of Pair<String, Foo>
                .flatMap(f -> f.tags.stream().map(s -> new AbstractMap.SimpleImmutableEntry<>(s, f)))
                //Then collect it up into a multimap.
                .collect(
                        Multimaps.toMultimap(
                                x -> x.getKey(),
                                x -> x.getValue(),
                                MultimapBuilder.hashKeys().arrayListValues()::build
                        )
                );
    

    I know the use of a pair class is a but ugly, but the key thing I wanted to show is the Multimaps.toMultmap collector. There's also a Multmaps.flatteningToMultimap for other use cases.

    0 讨论(0)
  • 2020-12-14 21:50
    ImmutableMultimap.Builder<String, Foo> builder = ImmutableMultimap.builder();
    list.forEach(foo -> foo.getTags().forEach(tag -> builder.put(tag, foo));
    return builder.build();
    
    0 讨论(0)
  • 2020-12-14 21:55

    You can use custom collector for this:

    Multimap<String, Foo> map = list.stream().collect(
        ImmutableMultimap::builder,
        (builder, value) -> value.getTags().forEach(tag -> builder.put(tag, value)),
        (builder1, builder2) -> builder1.putAll(builder2.build())
    ).build();
    

    This does not cause extra side effects (see here on this), is concurrent and more idiomatic.

    You can also extract these ad-hoc lambdas into a full-fledged collector, something like this:

    public static <T, K> Collector<T, ?, Multimap<K, T>> toMultimapByKey(Function<? super T, ? extends Iterable<? extends K>> keysMapper) {
        return new MultimapCollector<>(keysMapper);
    }
    
    private static class MultimapCollector<T, K> implements Collector<T, ImmutableMultimap.Builder<K, T>, Multimap<K, T>> {
        private final Function<? super T, ? extends Iterable<? extends K>> keysMapper;
    
        private MultimapCollector(Function<? super T, ? extends Iterable<? extends K>> keysMapper) {
            this.keysMapper = keysMapper;
        }
    
        @Override
        public Supplier<ImmutableMultimap.Builder<K, T>> supplier() {
            return ImmutableMultimap::builder;
        }
    
        @Override
        public BiConsumer<ImmutableMultimap.Builder<K, T>, T> accumulator() {
            return (builder, value) -> keysMapper.apply(value).forEach(k -> builder.put(k, value));
        }
    
        @Override
        public BinaryOperator<ImmutableMultimap.Builder<K, T>> combiner() {
            return (b1, b2) -> b1.putAll(b2.build());
        }
    
        @Override
        public Function<ImmutableMultimap.Builder<K, T>, Multimap<K, T>> finisher() {
            return ImmutableMultimap.Builder<K, T>::build;
        }
    
        @Override
        public Set<Characteristics> characteristics() {
            return Collections.emptySet();
        }
    }
    

    Then the collection would look like this:

    Multimap<String, Foo> map = list.stream().collect(toMultimapByKey(Foo::getTags));
    

    You can also return EnumSet.of(Characteristics.UNORDERED) from characteristics() method if the order is not important for you. This can make internal collection machinery act more efficiently, especially in case of parallel reduction.

    0 讨论(0)
  • 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<String, Foo> result = list.stream()
            .flatMap(foo -> foo.getTags().stream().map(tag -> Map.entry(tag, foo)))
            .collect(ImmutableSetMultimap.toImmutableSetMultimap(Map.Entry::getKey, Map.Entry::getValue));
    
    0 讨论(0)
提交回复
热议问题