Although, there is performance cost associated with forEachOrdered(), this can be used with elements that need to be processed in parallel. In such case, stream operations before/after the forEachOrdered() can still use the performance improvements.

Performance improvement with Parallel Stream

Parallel stream provides performance improvements depending on the number of CPUs available.

For smaller streams, the improvement may be limited because of overhead associated with multitasking. In fact, a stream that processes a small amount of data may actually run slower with parallelStream().

Parallel streams are useful on independent stream operations.i.e, result of the operation on one element of the stream is not dependent on result of another element of the stream.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

packagecom.topjavatutorial.java8examples;

importjava.util.ArrayList;

importjava.util.List;

publicclassParallelStreamDemo{

publicstaticvoidmain(String[]args){

List<Integer>numbers=newArrayList<Integer>();

for(inti=0;i<1000;i++){

numbers.add(i);

}

// Process data sequentially

longstartTime=System.currentTimeMillis();

numbers.stream().forEach(i->processElement(i));

longendTime=System.currentTimeMillis();

doubletimeTaken=(endTime-startTime)/1000;

System.out.println("Time taken with stream() : "+timeTaken

+" milliseconds");

// Process data in parallel

startTime=System.currentTimeMillis();

numbers.parallelStream().forEach(i->processElement(i));

endTime=System.currentTimeMillis();

timeTaken=(endTime-startTime)/1000;

System.out.println("Time taken with parallelStream() : "+timeTaken

+" milliseconds");

}

privatestaticvoidprocessElement(intnum){

try{

Thread.sleep(10);

}catch(InterruptedExceptione){

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

Output :

Time taken with stream() : 12.0 milliseconds Time taken with parallelStream() : 2.0 milliseconds