tmn*_*tmn 4 java lambda guava java-8 java-stream
为了提高效率,我经常遇到需要多地图地图的情况.我更愿意使用番石榴,ImmutableMap并ImmutableMultimap实现这一目标.
我借用并Collector为Guava 创建了几个实现,因此我可以利用Java 8流.例如,这是一个收集器ImmutableListMultimap.
public static <T, K, V> Collector<T, ?, ImmutableListMultimap<K, V>> toImmutableListMultimap(
        Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends V> valueMapper) {
    Supplier<ImmutableListMultimap.Builder<K, V>> supplier = ImmutableListMultimap.Builder::new;
    BiConsumer<ImmutableListMultimap.Builder<K, V>, T> accumulator = (b, t) -> b
            .put(keyMapper.apply(t), valueMapper.apply(t));
    BinaryOperator<ImmutableListMultimap.Builder<K, V>> combiner = (l, r) -> l.putAll(r.build());
    Function<ImmutableListMultimap.Builder<K, V>, ImmutableListMultimap<K, V>> finisher = ImmutableListMultimap.Builder::build;
    return Collector.of(supplier, accumulator, combiner, finisher);
}
我想为我当前的问题创建一个非常相似的收集器.我希望我的收藏家创建一个ImmutableMap<P,ImmutableMultimap<C,V>>,其中P是主地图的父键,并且C是子地图的子键.Function将提供两个lambdas来为每个T项目映射这些键.
这说起来容易做起来难.到目前为止,我所做的就是创建方法存根.
public static <T, P, C, V> Collector<T, ?, ImmutableMap<P, ImmutableMultimap<C,V>>> toPartitionedImmutableMultimap(
            Function<? super T, ? extends P> parentKeyMapper,
            Function<? super T, ? extends C> childKeyMapper,
            Function<? super T, ? extends V> valueMapper) {
}
因为Guava不可变集合构建器不允许查找,所以我发现自己使用可变的哈希映射来查找先前捕获的值,因此我只会在P键不存在时创建新的ImmutableMultimap.但这个过程很快就变得令人目不暇接.
有没有一种有效的方法来做到这一点?
你尝试过直截了当的方法吗?
collectingAndThen(
        groupingBy(
                parentKeyMapper,
                toImmutableListMultimap(childKeyMapper, valueMapper)
        ),
        ImmutableMap::copyOf
);
更新:上面的代码适用于JDK,但Eclipse编译器正在抱怨它.这是Eclipse将接受的版本:
public static <T, P, C, V> Collector<T, ?, ImmutableMap<P, ImmutableMultimap<C, V>>> toPartitionedImmutableMultimap(
        Function<? super T, ? extends P> parentKeyMapper,
        Function<? super T, ? extends C> childKeyMapper,
        Function<? super T, ? extends V> valueMapper) {
    return Collectors.collectingAndThen(
            Collectors.groupingBy(
                    parentKeyMapper,
                    SO29417692.<T,C,V>toImmutableListMultimap(childKeyMapper, valueMapper)
            ),
            ImmutableMap::<P,ImmutableMultimap<C,V>>copyOf
    );
}
| 归档时间: | 
 | 
| 查看次数: | 1356 次 | 
| 最近记录: |