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:
items.forEach(System.out::println);
Operation 2:

for (String item : items) 
{
   System.out.println(item);
}
Output (Same for Both)

Hello
Java
Developer
CoderMagnet



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)
items.stream().forEach(System.out :: print);

System.out.println("\n");

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

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.

No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.