One interesting feature of the new Stream API is that a Stream can be parallel, the operations are automatically done in parallel.  No explicit multi-threading code is required. The methods are stream() and parallelStream() which are default methods and have been written in Collection interface. With the help of these methods, we can write the code effectively.

Collection.parallelStream() returns parallel stream instance for calling collection. The Stream object can be used for different purpose. Let’s  look at below example:

Employee class which is being used as value object.


Output :

Average Salary : 47366.666666666664

In above example if you replace employeeList.parallelStream() with the output will be same. Now you might be thinking what is the difference in both these methods, anytime you want particular job using multiple threads in parallel cores, all you have to do is call method parallelStream() instead of stream() which executes a job sequential threads.  It is all up to you to decide which stream has to be used based on your requirement.

Parallel Array Operations:  the following operations have been added to Arrays in Java SE 8

  • Arrays.paralellSort()
  • Arrays.parallelPrefix()
  • Arrays.parallelSetAll()

The parallel features mentioned here  is for improved concurrency.

READ  Autoboxing in Java