Stream <stream>:flatMap与reduce

时间:2016-06-22 18:19:18

标签: java java-8 java-stream

如果我执行以下代码“连接”两个流

  • 首先通过flatMapping Stream<Stream<Integer>>
  • 然后使用Stream<Stream<Integer>>
  • 缩减Stream.concat()

我在两种情况下都获得了相同的正确结果,但过滤操作的数量不同。

public class FlatMapVsReduce {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        Predicate<Integer> predicate1 = i -> {
            System.out.println("testing first condition with " + i);
            return i == 3;
        };

        Predicate<Integer> predicate2 = i -> {
            System.out.println("testing second condition with " + i);
            return i == 7;
        };

        System.out.println("Testing with flatMap");
        Integer result1 =
            Stream.of(list.stream().filter(predicate1),
                      list.stream().filter(predicate2))
                  .flatMap(Function.identity())
                  .peek(i -> System.out.println("peeking " + i))
                  .findFirst()
                  .orElse(null);
        System.out.println("result1 = " + result1);

        System.out.println();
        System.out.println("Testing with reduce");
        Integer result2 =
            Stream.of(list.stream().filter(predicate1),
                      list.stream().filter(predicate2))
                  .reduce(Stream::concat)
                  .orElseGet(Stream::empty)
                  .peek(i -> System.out.println("peeking " + i))
                  .findFirst()
                  .orElse(null);
        System.out.println("result2 = " + result2);
    }
}

我在两种情况下都得到了预期的结果(3)。但是,第一个操作对集合的每个元素应用第一个过滤器,而第二个过滤器在满足一个元素时立即停止。输出是:

Testing with flatMap
testing first condition with 1
testing first condition with 2
testing first condition with 3
peeking 3
testing first condition with 4
testing first condition with 5
testing first condition with 6
testing first condition with 7
testing first condition with 8
testing first condition with 9
result1 = 3

Testing with reduce
testing first condition with 1
testing first condition with 2
testing first condition with 3
peeking 3
result2 = 3

为什么两者之间的行为存在差异? JDK代码是否可以在第一个场景中提高效率,而不是在第二个场景中提高效率,或者flatMap中是否存在使其无法实现的内容?

附录:以下替代方案与使用reduce的方案一样有效,但我仍然无法解释原因:

    Integer result3 = Stream.of(predicate1, predicate2)
                            .flatMap(c -> list.stream().filter(c).limit(1))
                            .peek(i -> System.out.println("peeking " + i))
                            .findFirst()
                            .orElse(null);
    System.out.println("result3 = " + result3);

1 个答案:

答案 0 :(得分:3)

flatMap in openJDK的实现,我理解的是flatMap将传入流的全部内容推送到下游:

result.sequential().forEach(downstreamAsInt);

另一方面,Stream::concat似乎正在处理拉力而不是立即发送所有内容。

我怀疑你的测试没有显示全貌:

  • flatMap中,仅在第一个流耗尽时才考虑第二个流。
  • reduce中,所有流都被推送到最终的连接流中,因为在输入流的所有内容都被消耗之前,缩减的对象没有意义。

这意味着使用其中一个取决于您的输入有多复杂。如果你有一个无限Stream<Stream<Integer>>,则reduce永远不会完成。