Upper Knowledge of Functional Streams With Parallel Streams in Java
Upper Knowledge of Functional Streams With Parallel Streams in Java
- by utk
Using functional streams with parallel streams in Java lets you write concise, efficient,
and thread-safe code to process large datasets in parallel. This takes advantage of multi-
core processors without manual thread handling.
java
CopyEdit
list.parallelStream() // instead of list.stream()
java
CopyEdit
import java.util.*;
import java.util.stream.*;
Dangerous:
java
CopyEdit
List<Integer> results = new ArrayList<>();
list.parallelStream().forEach(results::add); // May throw
ConcurrentModificationException
Safe:
java
CopyEdit
List<Integer> results = list.parallelStream()
.map(x -> x * 2)
.collect(Collectors.toList());
java
CopyEdit
ForkJoinPool customThreadPool = new ForkJoinPool(4);
customThreadPool.submit(() -> {
list.parallelStream()
.forEach(System.out::println);
}).get();