Sequential vs Parallel
Sequential
The external iteration typically means sequential code. The sequential code can be executed only by one thread.
Streams are designed to process elements in parallel.
Example
The following code computes the sum of squares of odd integers in the list in parallel.
import java.util.Arrays;
import java.util.List;
/*w w w . j ava2s. c o m*/
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
.filter(n -> n % 2 == 1)
.map(n -> n * n)
.reduce(0, Integer::sum);
System.out.println(sum);
}
}
What we did is just to replace stream()
with parallelStream()
.
Parallel computation is easy when using the internal iteration provided by the stream.
The code above generates the following result.