Enhanced For Loop (For-Each Loop) in Java
There are four types of loops in Java – for-loop, for-each loop, while loop, and do-while loop. This post provides an overview of the for-each construct in Java.
The foreach-construct is a control flow statement introduced in Java 1.5, making it easier to iterate over items in an array or a Collection. The For-Each loop is usually used as a substitute for the standard for-statement when a 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:
|
1 2 3 |
for (Type item: iterableCollection) { // Do something to the item } |
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 maintains 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 the following code, which uses an iterator to traverse a collection.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; class Main { public static void main(String[] args) { List<String> colors = new ArrayList<>(Arrays.asList("Blue", "Red", "Green")); // traversing list using an iterator for (Iterator<String> itr = colors.iterator(); itr.hasNext(); ) { System.out.println(itr.next()); } } } |
Output:
Blue
Red
Green
The above code uses an iterator to traverse the list, which is plain ugly and difficult to read. Furthermore, it has a 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 of by the compiler itself, and the type safety of the code is preserved.
Now let’s see how the above code is transformed with the for-each construct:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; class Main { public static void main(String[] args) { List<String> colors = new ArrayList<>(Arrays.asList("Blue", "Red", "Green")); // traversing list using for-each construct for (String i: colors) { System.out.println(i); } } } |
Output:
Blue
Red
Green
When not to use Enhanced for-loop?
We have seen the advantages of the for-each loop over the iterator. But ForEach is not a plain replacement for the 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,
- We cannot remove any element from the collection while traversing it using
ForEach. But it can be easily done using the iterator’sremove()method. - We cannot modify elements in an array or a collection as you traverse it using ForEach.
- We can’t iterate over multiple collections in parallel using
ForEach.
More Examples
1. Iterating over an array
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Non-Generic version public static void iterateArray (int[] A) { for (int i: A) { System.out.println(i); } } // Generic version public static<T> void iterateObjectArray (T[] A) { for (T i: A) { System.out.println(i); } } |
2. Iterating over a list
|
1 2 3 4 5 |
public static<T> void iterateList(List<T> list) { for (T e: list) { System.out.println(e); } } |
3. Iterating over a set
|
1 2 3 4 5 |
public static<T> void iterateSet(Set<T> set) { for (T e: set) { System.out.println(e); } } |
4. Iterating over a map
|
1 2 3 4 5 |
public static<K, V> void iterateMap(Map<K, V> map) { for (Map.Entry<K, V> entry: map.entrySet()) { System.out.println("{" + entry.getKey() + ":" + entry.getValue() + "}"); } } |
That’s all about enhanced for loop in Java.
Also Read:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)