Parallel Streams in Java 8

Sanjay Singh
1 min readNov 14, 2019

--

1. Parallel Streams in Java 8

Parallel streams divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. On the other hand sequential streams work just like for-loop using a single core.

The tasks provided to the streams are typically the iterative operations performed on the elements of a collection or array or from other dynamic sources. Parallel execution of streams run multiple iterations simultaneously in different available cores.

1.2 When to use Parallel Streams?

· They should be used when the output of the operation is not needed to be dependent on the order of elements present in source collection (i.e. on which the stream is created)

· Parallel Streams can be used in case of aggregate functions

· Parallel Streams quickly iterate over the large-sized collections

· Parallel Streams can be used if developers have performance implications with the Sequential Streams

· If the environment is not multi-threaded, then Parallel Stream creates thread and can affect the new requests coming in

Example How to use Parallel Streams

List<String> strings = Arrays.asList(“abc”, “”, “bc”, “efg”, “abcd”,””, “jkl”);

//get count of empty string

long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet