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