Java Stream: difference between forEach and forEachOrdered

Premises : I already read this question and others, but I need some clarification.

I understand that the method Stream.forEachmakes a difference (not only) when working with parallel threads, and this explains why this

//1
Stream.of("one ","two ","three ","four ","five ","six ")
.parallel()
.forEachOrdered(item -> System.out.print(item));

prints

one two three four five six

But when it comes to intermediate operations, ordering is no longer guaranteed when the flow is parallelized. So this code

//2
Stream.of("one ","two ","three ","four ","five ","six ")
.parallel()
.peek(item -> System.out.print(item))
.forEachOrdered(item -> System.out.print(""));

will print something like

four six five one three two 

Is it possible to say that a method forEachOrderedonly affects the order of elements in its own execution? Intuitively, I think that the example //1matches

//3
Stream.of("one ","two ","three ","four ","five ","six ")
.parallel()
.peek(item -> System.out.print("")) //or any other intermediate operation
.sequential()
.forEach(item -> System.out.print(item));

Is my intuition wrong? Am I missing something on the whole mechanism?

+2
2

# 3 # 1, parallel() sequential() , . , № 3 . №3 Stream API, / . ( , ., , ), , ( ). , ​​ forEachOrdered(), parallel()/sequential() , (. ).

, : . , .

+3

, , forEachOrdered, . , , .sequential().forEach(…).

sequential , , , forEach, , peek. parallel sequential , , .

, forEach - , - . Does Stream.forEach ?

Stream.forEachOrdered :

, , . , , .

, , Thread.currentThread(), . , , . .

+3

Source: https://habr.com/ru/post/1665429/


All Articles