takeWhile()与flatmap的工作方式不同 [英] takeWhile() working differently with flatmap

查看:112
本文介绍了takeWhile()与flatmap的工作方式不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建使用takeWhile的片段来探索它的可能性。与flatMap结合使用时,行为与预期不符。请找到下面的代码段。

I am creating snippets with takeWhile to explore its possibilities. When used in conjunction with flatMap, the behaviour is not in line with the expectation. Please find the code snippet below.

String[][] strArray = {{"Sample1", "Sample2"}, {"Sample3", "Sample4", "Sample5"}};

Arrays.stream(strArray)
        .flatMap(indStream -> Arrays.stream(indStream))
        .takeWhile(ele -> !ele.equalsIgnoreCase("Sample4"))
        .forEach(ele -> System.out.println(ele));

实际产出:

Sample1
Sample2
Sample3
Sample5

ExpectedOutput:

ExpectedOutput:

Sample1
Sample2
Sample3

期望的原因是takeWhile应该执行直到条件内部变为真。我还在flatmap中添加了printout语句以进行调试。这些流只返回两次,符合期望值。

Reason for the expectation is that takeWhile should be executing till the time the condition inside turns true. I have also added printout statements inside flatmap for debugging. The streams are returned just twice which is inline with the expectation.

但是,如果链中没有flatmap,这样就可以了。

However, this works just fine without flatmap in the chain.

String[] strArraySingle = {"Sample3", "Sample4", "Sample5"};
Arrays.stream(strArraySingle)
        .takeWhile(ele -> !ele.equalsIgnoreCase("Sample4"))
        .forEach(ele -> System.out.println(ele));

实际产出:

Sample3

此处实际输出与预期输出匹配。

Here the actual output matches with the expected output.

免责声明:这些片段仅用于代码练习,不提供任何有效的用例。

Disclaimer: These snippets are just for code practise and does not serve any valid usecases.

更新:
错误 JDK-8193856 :修复将作为JDK 10的一部分提供。
更改将更正 whileOps
Sink :: accept

Update: Bug JDK-8193856: fix will be available as part of JDK 10. The change will be to correct whileOps Sink::accept

@Override 
public void accept(T t) {
    if (take = predicate.test(t)) {
        downstream.accept(t);
    }
}

更改实施:

@Override
public void accept(T t) {
    if (take && (take = predicate.test(t))) {
        downstream.accept(t);
    }
}


推荐答案

这是JDK 9中的一个错误 - 来自问题#8193856

This is a bug in JDK 9 - from issue #8193856:


takeWhile 错误地假设上游操作支持并取消取消,遗憾的是不是这样的 flatMap

takeWhile is incorrectly assuming that an upstream operation supports and honors cancellation, which unfortunately is not the case for flatMap.

这篇关于takeWhile()与flatmap的工作方式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆