Enhanced For Loop (For-Each Loop) in Java

There are four types of loop in Java – for loop, for-each loop, while loop, and do-while loop. This post provides an overview of for-each construct in Java.


 

The foreach-construct is a control flow statement, introduced in Java 1.5, which makes it easier to iterate over items in an array or a Collection. ForEach is usually used as substitute for a standard for statement when loop counter is not really needed and every element in the collection has to be processed. It is also referred to as the Enhanced for Loop, the For-Each Loop, and the ForEach statement.

The syntax of the enhanced for loop is:

 
The above loop reads as “for each Type item in iterableCollection” where the colon (:) means in.

Note the difference between the standard for loop and for-each loop. The syntax is greatly simplified and the loop maintain no explicit counter: they essentially say “do this to everything in this collection”, rather than “do this x times”.

 

Need for Enhanced for Loop?

Consider below code which uses an iterator to traverse a collection.

 

Download   Run Code

Output:

Blue
Red
Green

 
Above code uses an iterator to traverse the list which is just plain ugly and difficult to read. Furthermore, it has lot of potential for errors since it uses generics and the iterator variable is accessed several times in the code. The for-each construct simplifies the code by hiding the complexity behind the scenes. (ForEach internally invokes the iterator() method). Also, the generics are taken care by the compiler itself and type safety of the code is preserved.

Now let’s see how above code is transformed with the for-each construct:

 

Download   Run Code

Output:

Blue
Red
Green

 

When not to use Enhanced for Loop?

We have seen the advantages of for-each loop over the iterator. But ForEach is not plain replacement for iterator. Since for-each loop hides the iterator for a collection and the index variable in an array, there are few things that only an iterator and simple for-loop can do. For instance,

  1. We cannot remove any element from the collection while traversing it using ForEach. But it can be easily done using the iterator’s remove() method.
     
  2. We cannot modify elements in an array or a collection as you traverse it using ForEach.
     
  3. We can’t iterate over multiple collections in parallel using ForEach.

 

More Examples

 

1. Iterating over an Array

 

2. Iterating over a List

 

3. Iterating over a Set

 

4. Iterating over a Map

 
That’s all about Enhanced for loop in Java. Thanks for reading.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

 
Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of