[英]Java 8 Streams, perform part of the work as parallel stream and the other as sequential stream
[英]Java Stream API - Parallel and Sequential Streams
I am new to the Stream API.I have a question about Stream API,specifically the parallel and sequential stream. 问题是:例如,如果我有这样的伪代码:
someStream
.parallel()
.filter(some_predicate)
.sequential()
.map(some_mapping_function)
.terminal_operation();
Is the Stream API going to execute filter in parallel and mapping sequentially,or does it merely change the "parallel-characteristic" of the stream,so,in this example,the stream is going to be sequential?
对sequential()
和parallel()
的调用只是改变了整个stream 的模式。 调用终端操作时 stream 处于哪种模式是使用的模式。 在您的情况下,由于 sequence sequential()
在parellel()
之后,您的 stream 将按顺序执行。
这由Stream
接口记录:
Stream 管道可以按顺序或并行执行。 此执行模式是 stream [强调添加]的属性。 流是通过初始选择顺序或并行执行来创建的。 (例如,
Collection.stream()
创建一个顺序 stream,而Collection.parallelStream()
创建一个并行。)执行模式的选择可以通过BaseStream.sequential()
或BaseStream.parallel()
方法进行修改,并且可以使用BaseStream.isParallel()
方法查询。
和java.util.stream
package:
根据调用终端操作的 stream 的模式,顺序或并行执行 stream 流水线。 stream 的顺序或并行模式可以通过
BaseStream.isParallel()
方法确定,流的模式可以通过BaseStream.sequential()
和BaseStream.parallel()
操作进行修改。 最新的顺序或并行模式设置适用于整个 stream 管道的执行[强调添加] 。
获得此类问题答案的最快方法是创建一个非常简单的测试。 我试过这样的事情:
public static void main(String args[]) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<50;i++){
list.add(i);
}
list.stream()
.sequential()
.map(a->{
System.out.println("sequential " + a);
return a;
})
.parallel()
.forEach(a-> System.out.println("parallel " + a));
System.out.println();
System.out.println();
list.stream()
.parallel()
.map(a->{
System.out.println("parallel " + a);
return a;
})
.sequential()
.forEach(a-> System.out.println("sequential " + a));
}
当您运行代码并分析这两个流的 output 时,您可以看到第一个是并行的,第二个是顺序的。
基于此,我们可以推断只有最后一个parallel/sequential
调用很重要——它基本上是覆盖标志。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.