Difference between forEachOrdered () and sequential () methods of Java 8?

I am working on a java 8 parallel thread and want to print elements in a parallel thread - this is some order (e.g. insertion order, reverse order or sequential order).

Why did I try the following code:

        System.out.println("With forEachOrdered:");
        listOfIntegers
            .parallelStream()
            .forEachOrdered(e -> System.out.print(e + " "));
        System.out.println("");

        System.out.println("With Sequential:");
        listOfIntegers.parallelStream()
                    .sequential()
                    .forEach(e -> System.out.print(e + " "));

And for both of them, I got the same result as follows:

With forEachOrdered:
1 2 3 4 5 6 7 8 
With Sequential:
1 2 3 4 5 6 7 8 

from the api documentation, I see that:

forEachOrdered -> This is a terminal operation.

and

sequential -> This is an intermediate operation.

So my question is: which one is better to use? and in which scenarios should you be preferable to others?

+4
source share
3 answers

listOfIntegers.parallelStream().sequential().forEach() Stream, Stream, listOfIntegers.stream().forEach() Stream.

listOfIntegers.parallelStream().forEachOrdered(e -> System.out.print(e + " ")) Stream, , Stream ( Stream ). .

- listOfIntegers.parallelStream().sequential(). Stream, Stream?

+3

- , :

 .parallelStream()
 .forEachOrdered(...)

, . map :

.map(...)
.parallelStream()
.forEachOrdered(...)

map ( ), , ( forEachOrdered). .

, , :

.parallelStream()
.map()
.sorted()
.// other operations

sorted , . , sorted , "" ( forEachOrdered) .

:

listOfIntegers.parallelStream()
                .sequential()
                .forEach(e -> System.out.print(e + " "))

, , , , . , :

 .map...
 .filter...
 .parallel()
 .map...
 .sequential

, , - , - . , forEach , , , , ( forEach ), .

+3

. . . , Collection.stream() , Collection.parallelStream() . BaseStream.sequential() BaseStream.parallel().

:

listOfIntegers.parallelStream().sequential()

:

listOfIntegers.stream()

parallel stream, . forEach forEachOrdered , forEach , forEachOdered . parallelStream() forEachOrdered - , - . , forEachOrdered . , , beforeEachOder, , .

Oracle does not document what happens when you change the execution mode of a thread in a pipeline several times. It is unclear whether the last change matters or whether the calls that are called after the call parallel()can be executed in parallel, and the operations that are called after the call sequential()will be executed in sequence.

+1
source

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


All Articles