Junior — Middle
How are parallel streams implemented in the Stream API?
sobes.tech AI
Answer from AI
In Java Stream API, parallel streams are implemented using the parallelStream() method or by calling parallel() on an existing stream. This allows operations on collection elements to be performed in parallel, utilizing multiple threads from the ForkJoinPool.
Working principle:
- When
parallelStream()is called, a parallel stream is created. - Operations on elements are divided into subtasks, which are executed in multiple threads.
- Results are automatically combined.
Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
.mapToInt(Integer::intValue)
.sum();
It is important to remember that parallel streams are effective with large data volumes and when operations are independent and have no side effects. Also, consider the overhead of creating and synchronizing threads.