相关疑难解决方法(0)

为什么flatMap()之后的filter()在Java流中"不完全"懒惰?

我有以下示例代码:

System.out.println(
       "Result: " +
        Stream.of(1, 2, 3)
                .filter(i -> {
                    System.out.println(i);
                    return true;
                })
                .findFirst()
                .get()
);
System.out.println("-----------");
System.out.println(
       "Result: " +
        Stream.of(1, 2, 3)
                .flatMap(i -> Stream.of(i - 1, i, i + 1))
                .flatMap(i -> Stream.of(i - 1, i, i + 1))
                .filter(i -> {
                    System.out.println(i);
                    return true;
                })
                .findFirst()
                .get()
);
Run Code Online (Sandbox Code Playgroud)

输出如下:

1
Result: 1
-----------
-1
0
1
0
1
2
1
2
3
Result: -1
Run Code Online (Sandbox Code Playgroud)

从这里我看到,在第一种情况下stream真的表现得懒惰 - 我们使用findFirst()所以一旦我们有第一个元素我们的过滤lambda没有被调用.然而,在使用flatMaps的第二种情况下,我们看到尽管找到满足过滤条件的第一个元素(它只是任何第一个元素,因为lambda总是返回true),流的其他内容仍然通过过滤函数被馈送.

我试图理解为什么它表现得像这样,而不是在第一个元素计算后放弃,如第一种情况.任何有用的信息将不胜感激.

java lambda java-8 java-stream

70
推荐指数
4
解决办法
6190
查看次数

Java 8 流上的缓冲区运算符

我正在尝试编写一个 java 8 流收集器,它反映了rxjava 缓冲区运算符的功能

我有一个工作代码:

// This will gather numbers 1 to 13 and combine them in groups of
// three while preserving the order even if its a parallel stream.
final List<List<String>> triads = IntStream.range(1, 14)
        .parallel()
        .boxed()
        .map(Object::toString)
        .collect(ArrayList::new, accumulator, combiner);

System.out.println(triads.toString())
Run Code Online (Sandbox Code Playgroud)

这里的累加器是这样的:

final BiConsumer<List<List<String>>, String> accumulator = (acc, a) -> {
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append("Accumulator|");
      stringBuilder.append("Before: ").append(acc.toString());
      int accumulatorSize = acc.size();
      if (accumulatorSize == 0) {
        List<String> newList = new ArrayList<>();
        newList.add(a);
        acc.add(newList); …
Run Code Online (Sandbox Code Playgroud)

java functional-programming java-8 rx-java java-stream

1
推荐指数
1
解决办法
3543
查看次数