如果我使用 parallelStream()
而不是 stream()
,filter
链接会改变结果吗?
我尝试了几千条记录,并且在几次迭代中输出显得一致。但由于这涉及线程,(并且我找不到足够的相关 Material 来讨论这种组合)我想双重确保并行流不会以任何方式影响过滤器链接的输出。示例代码:
List<Element> list = myList.parallelStream()
.filter(element -> element.getId() > 10)
.filter(element -> element.getName().contains("something"))
.collect(Collectors.toList());
最佳答案
简短回答:否。
文档中的 filter
操作需要 non-interferening和 stateless应用于每个元素的谓词以确定是否应将其作为新流的一部分包含在内。
您应该考虑的几个方面是 -
- 并发集合除外(您在现有代码中选择什么作为
myList
)-
For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline.
- 数据源的状态(过滤器操作中的
myList
及其元素
不会发生变化)
Note also that attempting to access mutable state from behavioral parameters presents you with a bad choice with respect to safety and performance;
此外,请考虑一下,您的 filter
操作中的哪些内容会受到多个线程的影响。给定当前代码,没有任何功能,只要执行这两个操作,无论执行它们的线程如何,您都会得到一致的结果。
关于java - 具有过滤器链接的 ParallelStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62785292/