本文介绍了从Java 8流创建Guava Multimap的最干净方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List<Foo>,想要一个Multimap<String, Foo>,我们在其中按getId()函数对Foo进行了分组.

I have a List<Foo> and want a Multimap<String, Foo> where we've grouped the Foo's by their getId() function.

我正在使用Java 8及其出色的功能,您可以这样做:

I am using Java 8 and its almost awesome in that you can do:

List<Foo> foos = ...
Map<String, List<Foo>> foosById = foos.stream().collect(groupingBy(Foo::getId));

但是,我有很多需要MultiMap<String, Foo>的代码,所以这并没有为我节省任何东西,我回到使用for循环创建我的Multimap的过程.是否有一个不错的功能性"功能?我想念的方式吗?

However, I have a good amount of code that wants a MultiMap<String, Foo> so this doesnt save me anything and I'm back to using a for-loop to create my Multimap. Is there a nice "functional" way that I am missing?

推荐答案

您可以只使用Guava Multimaps工厂:

You can just use the Guava Multimaps factory:

Multimaps.index(foos, Foo::getId);

或使用Collector接口包装对Multimaps.index的调用(如下所示,在未优化的朴素实现中).

or wrap a call to Multimaps.index with a Collector interface (shown below, in an unoptimized naive implementation).

Multimap<String, Foo> collect = foos.stream().collect(MultimapCollector.toMultimap(Foo::getId));

和收集器:

public class MultimapCollector<T, K, V> implements Collector<T, Multimap<K, V>, Multimap<K, V>> {

    private final Function<T, K> keyGetter;
    private final Function<T, V> valueGetter;

    public MultimapCollector(Function<T, K> keyGetter, Function<T, V> valueGetter) {
        this.keyGetter = keyGetter;
        this.valueGetter = valueGetter;
    }

    public static <T, K, V> MultimapCollector<T, K, V> toMultimap(Function<T, K> keyGetter, Function<T, V> valueGetter) {
        return new MultimapCollector<>(keyGetter, valueGetter);
    }

    public static <T, K, V> MultimapCollector<T, K, T> toMultimap(Function<T, K> keyGetter) {
        return new MultimapCollector<>(keyGetter, v -> v);
    }

    @Override
    public Supplier<Multimap<K, V>> supplier() {
        return ArrayListMultimap::create;
    }

    @Override
    public BiConsumer<Multimap<K, V>, T> accumulator() {
        return (map, element) -> map.put(keyGetter.apply(element), valueGetter.apply(element));
    }

    @Override
    public BinaryOperator<Multimap<K, V>> combiner() {
        return (map1, map2) -> {
            map1.putAll(map2);
            return map1;
        };
    }

    @Override
    public Function<Multimap<K, V>, Multimap<K, V>> finisher() {
        return map -> map;
    }

    @Override
    public Set<Characteristics> characteristics() {
        return ImmutableSet.of(Characteristics.IDENTITY_FINISH);
    }
}

这篇关于从Java 8流创建Guava Multimap的最干净方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 20:26