.map返回的Java-8 Stream将是并行还是顺序?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了.map返回的Java-8 Stream将是并行还是顺序?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2359字,纯文字阅读大概需要4分钟。
内容图文
![.map返回的Java-8 Stream将是并行还是顺序?](/upload/InfoBanner/zyjiaocheng/819/bf5963ebd416457c9fe6e265608647aa.jpg)
map或mapToObj方法返回的流总是顺序的,还是取决于调用流的状态是否是并行的?
IntStream的文档没有明确回答这个问题,或者我无法理解它:
我想知道来自以下示例的流是否会并行到最后,或者它会在某个时刻发生变化.
IntStream.range(1, array_of_X.size())
.parallel()
.mapToObj (index -> array_of_X.get(index)) // mapping#1
.filter (filter_X)
.map (X_to_Y) //mapping#2
.filter (filter_Y)
.mapToInt (obj_Y_to_int) //mapping#3
.collect(value -> Collectors.summingInt(value));
解决方法:
不,它永远不会改变(除非你自己明确地改变它).
您编写的内容对应于Stream管道,单个管道具有单一方向:并行或顺序.因此,没有“并行到最后”,因为整个流水线将并行执行或者将按顺序执行.
引用Stream package Javadoc:
The only difference between the serial and parallel versions of this example is the creation of the initial stream, using “
parallelStream()
” instead of “stream()
“. When the terminal operation is initiated, the stream pipeline is executed sequentially or in parallel depending on the orientation of the stream on which it is invoked. Whether a stream will execute in serial or parallel can be determined with theisParallel()
method, and the orientation of a stream can be modified with theBaseStream.sequential()
andBaseStream.parallel()
operations. When the terminal operation is initiated, the stream pipeline is executed sequentially or in parallel depending on the mode of the stream on which it is invoked.
这意味着Stream管道更改其方向的唯一方法是调用sequential()或parallel()方法之一.由于这是Stream API的全局,因此不是为每个操作编写,而是在Javadoc包中编写.
使用您的问题中的代码,Stream管道将并行执行,因为您通过调用parallel()明确地更改了Stream方向.
值得注意的是,Stream的最终调整将是对parallel()或sequential()的最后调用.请考虑以下三个示例:
public static void main(String[] args) {
System.out.println(IntStream.range(0, 10).isParallel());
System.out.println(IntStream.range(0, 10).parallel().isParallel());
System.out.println(IntStream.range(0, 10).parallel().map(i -> 2*i).sequential().isParallel());
}
>第一个将打印为false,因为IntStream.range返回顺序Stream
>第二个将打印为true,因为我们调用了parallel()
>第三个将打印为false,因为即使我们在管道中调用parallel(),我们之后调用sequential(),因此它将Stream管道的总方向重置为serial.
请注意,仍然引用:
The stream implementations in the JDK create serial streams unless parallelism is explicitly requested.
因此,除非您明确要求并行流,否则您要检索的每个Stream都将是顺序的.
内容总结
以上是互联网集市为您收集整理的.map返回的Java-8 Stream将是并行还是顺序?全部内容,希望文章能够帮你解决.map返回的Java-8 Stream将是并行还是顺序?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。