Last Updated: November 21, 2017
·
18.38K
· warfox

Java 8 Stream API vs for-each loop

Exhibit A. The [for-each][for-each] loop

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

Exhibit B. The [stream api][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]stream-api in Java 8 is that, we can easily implement parallelism when using the stream api with [collection.parallelStream()][collection-parallel-stream]. Whereas, in for-each loop you will have to handle threads on your own.

Exhibit C. The [parallel stream][collection-parallel-stream]

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

[stream-api]: http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
[collection-stream]: http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#stream---
[collection-parallel-stream]: http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#parallelStream---
[for-each]: http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html