Member-only story
What are the differences between sequential and parallel streams?
100 Days 100+ Interview Questions
Welcome back to our 100 Days 100+ Interview Questions series.
In our last blog, we discussed Stream API, where we discussed Parallel streams and wanted to give more info regarding that. Here it is for you.
Sequential Stream
Let’s consider a scenario where we have a large set of numbers let’s say in millions and you want to process them.
Let’s consider the following example where 1000K numbers are there and we wanted to find sum of numbers from them.
@Test
public void sequentialStreamTest() {
List<Integer> numbers = IntStream.rangeClosed(1, 1_000_000).boxed().toList();
long startTime = System.currentTimeMillis();
long sum = numbers.stream().filter(n -> n % 2 == 0).mapToLong(Integer::intValue).sum();
long endTime = System.currentTimeMillis();
System.out.println("Sequence Stream Result: " + sum);
System.out.println("Time Taken: " + (endTime - startTime));
}
Sequential Stream Result: 250000500000
Time Taken: 50
Here if you see we have 1000K integers and we want to find the sum of even numbers within the dataset. Time taken is 50 ms.
- One thing we can understand is here our…