Java 8 Stream API - Java 9 Collectors.flatMapping 在 Java 8 中重写

2022-09-03 12:12:03

以来,我接触到了一个名为Collectors.flatMapping的新功能,该功能作为分组或分区的下游发生。例如(从这里取的例子):

List<List<Integer>> list = Arrays.asList(
    Arrays.asList(1, 2, 3, 4, 5, 6), 
    Arrays.asList(7, 8, 9, 10));

Map<Integer, List<Integer>> map =list.stream()
    .collect(Collectors.groupingBy(
         Collection::size,
         Collectors.flatMapping(
             l -> l.stream().filter(i -> i % 2 == 0),
             Collectors.toList())));

{4=[8, 10], 6=[2, 4, 6]}

这是一种相当优雅的方式,仅使用3个收藏家。我需要在尚未受支持的情况下在中重写收集器。我的尝试使用6个收集器,这是一个非常广泛的用法,我无法找到使用较少它们的方法:

Map<Integer, List<Integer>> map = list.stream()
    .collect(Collectors.groupingBy(
        Collection::size,
        Collectors.collectingAndThen(
            Collectors.mapping(
                l -> l.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()),
                Collectors.toList()),
            i -> i.stream().flatMap(j -> j.stream()).collect(Collectors.toList()))));

有没有一种更短更好的方法单独使用


答案 1

我会向后移植。它只需要 2 个方法和 1 个类,没有其他依赖项。flatMapping

此外,当需要升级到 Java 9 时,您可以弃用您的版本,并将其的任何用法替换为正确的版本。

以下代码取自 JDK。我没有写它。我已经用你的示例测试了它,它返回相同的结果。

class Nikollectors
{
   public static <T, U, A, R> Collector<T, ?, R> flatMapping(Function<? super T, ? extends Stream<? extends U>> mapper, Collector<? super U, A, R> downstream) {
        BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();
        return new CollectorImpl<>(downstream.supplier(),
            (r, t) -> {
                try (Stream<? extends U> result = mapper.apply(t)) {
                    if (result != null)
                        result.sequential().forEach(u -> downstreamAccumulator.accept(r, u));
                }
            },
            downstream.combiner(), downstream.finisher(),
            downstream.characteristics());
    }

   private static class CollectorImpl<T, A, R> implements Collector<T, A, R>
   {
        private final Supplier<A> supplier;
        private final BiConsumer<A, T> accumulator;
        private final BinaryOperator<A> combiner;
        private final Function<A, R> finisher;
        private final Set<Characteristics> characteristics;

        CollectorImpl(Supplier<A> supplier,
                      BiConsumer<A, T> accumulator,
                      BinaryOperator<A> combiner,
                      Function<A,R> finisher,
                      Set<Characteristics> characteristics) {
            this.supplier = supplier;
            this.accumulator = accumulator;
            this.combiner = combiner;
            this.finisher = finisher;
            this.characteristics = characteristics;
        }

        CollectorImpl(Supplier<A> supplier,
                      BiConsumer<A, T> accumulator,
                      BinaryOperator<A> combiner,
                      Set<Characteristics> characteristics) {
            this(supplier, accumulator, combiner, castingIdentity(), characteristics);
        }

        @Override
        public BiConsumer<A, T> accumulator() {
            return accumulator;
        }

        @Override
        public Supplier<A> supplier() {
            return supplier;
        }

        @Override
        public BinaryOperator<A> combiner() {
            return combiner;
        }

        @Override
        public Function<A, R> finisher() {
            return finisher;
        }

        @Override
        public Set<Characteristics> characteristics() {
            return characteristics;
        }
    }

   private static <I, R> Function<I, R> castingIdentity() {
       return i -> (R) i;
   }
}

示例用法:

Map<Integer, List<Integer>> map =list.stream()
    .collect(Collectors.groupingBy(
         Collection::size,
         Nikollectors.flatMapping( // <<<
             l -> l.stream().filter(i -> i % 2 == 0),
             Collectors.toList()
        )
    )
);

答案 2

对于这个特殊情况,我想这将是一个更简单的版本:

Map<Integer, List<Integer>> map =
        list.stream()
            .collect(Collectors.toMap(
                Collection::size,
                x -> x.stream().filter(y -> y % 2 == 0).collect(Collectors.toList())
            ));

如果涉及合并(两个具有相同大小的集合),我会添加一个非常简单的函数:merge

 Map<Integer, List<Integer>> map =
        list.stream()
            .collect(Collectors.toMap(
                Collection::size,
                x -> x.stream().filter(y -> y % 2 == 0).collect(Collectors.toCollection(ArrayList::new)),
                (left, right) -> {
                    left.addAll(right);
                    return left;
                }
            ));

否则,我同意Michael在这个评论中的观点,这并不难向后移植到java-8。


推荐