21hetg
Last Updated: November 21, 2017
·
10.41K
· warfox

Java 8 Stream API vs for-each loop

Exhibit A. The for-each loop

List<Integer> array = Arrays.asList(1,2,3,4,5);
for(Integer i: array) {
    extremelyComplexCalculation(i);
}

Exhibit B. The stream api

List<Integer> array = Arrays.asList(1,2,3,4,5);
array.stream().forEach((i) -> {
    extremelyComplexCalculation(i);
});

It may seem Java 8's stream api is a bit verbose than the for-each loop for collections. And we wonder what benefit can come from it.

The difference between for-each loop and using stream api (collection.stream()) in Java 8 is that, we can easily implement parallelism when using the stream api with collection.parallelStream(). Whereas, in for-each loop you will have to handle threads on your own.

Exhibit C. The parallel stream

List<Integer> array = Arrays.asList(1,2,3,4,5);
array.parallelStream().forEach((i) -> {
    extremelyComplexCalculation(i);
});