Java — 8 | Parallel vs Sequential Stream with Example

Amar Balu
The Fresh Writes
Published in
4 min readFeb 1, 2023

--

Stream is introduced to easy the process of iteration over the elements of collections. In parallel Stream, the process is executed in parallel and so it uses multiple core processor to execute it fast.

Image Source : https://javadeveloperzone.com/spring-boot/spring-boot-tutorial/

Streams is used to improve the speed of processing for bulk data without actually storing the data in anywhere.

It doest not modify the existing data source instead it uses the stream processing to do modification in the stream and when needed it again need to be stored using any other collection framework.

Sequential Stream in Java

By default, all the streams are executed in the Sequential order, so that the processing and storing when needed the order is maintained.

public class SequentialStream {
public static void main(String[] args) throws Exception {
List<Integer> listOfNumbers = Arrays.asList(1, 2, 3, 4);
listOfNumbers.stream().forEach(s -> System.out.print(" "+s));
}
}

Here the output of this stream function is Sequential and is as follows.

1 2 3 4

We can also try by trying to print a Stream of 100 numbers in Stream and let’s calculate the time it has taken.

public class Streams {
/**
* @param…

--

--

Amar Balu
The Fresh Writes

I'm a front-end developer. I love React and Redux, Java, and Data Science. I write code for fun!. Join our publication : https://medium.com/thefreshwrites