java8 map并行_.map返回的Java-8 Stream将是并行还是顺序?

Java 8 中的 Stream 管道一旦设定为并行或顺序,将保持该模式直到结束。在示例代码中,由于调用了 `.parallel()`,整个管道将会并行执行。`map` 方法不会改变流的方向,流的并行性取决于最后一个设定的 `.sequential()` 或 `.parallel()` 方法。默认情况下,Stream 是顺序的,必须通过 `.parallel()` 明确转换为并行流。
摘要由CSDN通过智能技术生成

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管道,单个管道具有单一方向:并行或顺序.因此,没有“并行到最后”,因为整个流水线将并行执行或者将按顺序执行.

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 the isParallel() method, and the orientation of a stream can be modified with the BaseStream.sequential() and BaseStream.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都将是顺序的.

标签:java,java-8,java-stream

来源: https://codeday.me/bug/20190528/1168035.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值