Wednesday, 13 July 2016

forEach vs Enhanced For Loop in Java 8

When to use Java 8 forEach() over Enhanced For loop

Well in Java 8 you have an option to call the forEach() method over any iterable.
This is simply iterable.forEach(action), where forEach() performs the given action for
each element of the Iterable until all elements have been processed or the action throws an exception.

In normal scenarios there is absolutely no noticeable difference in performance.
So an operation like 1 and 2 this will yield similar results.

List<String> items = Arrays.asList("Hello", "Java", "Developer","CoderMagnet");

Operation 1:
Operation 2:

for (String item : items) 
Output (Same for Both)


So where is the difference????

The main advantage of forEach() is observed when it is invoked over a Java8 parallel stream.Parallel
execution reduces processing time. But unlike the previous example the sequential order is not maintained.
Long story short, forEach() over parallel streams will execute much faster.

// Normal Stream (Slower, sequential order maintained) :: print);


// Parallel Stream (Executes much faster, sequential order not maintained)
items.parallelStream().forEach(System.out :: print);

Hello Java Developer CoderMagnet 

Developer CoderMagnet Java Hello 

The Java8 forEach() should be used to boost performance in situations where parallel executions
can boost performance. But we should remember that parallel execution will not maintain the
sequential nature of data iteration.