In this guide, we will discuss for-each loop in detail with the help of examples. In Java, the for-each loop is used to iterate arrays or collections. It is easier to use than traditional for loop, this is why it is also known as enhanced for loop.
Syntax
Syntax of for-each loop:
for (Type element : collection) {
// Use element
}
Here, Type
is the type of the elements in the collection, for example, int, String etc. The element
is a variable that holds each element in the collection during each iteration, and collection
is the array or collection that you want to iterate over.
Examples
Let’s see few examples where we are using for-each loop to iterate various collections.
Iterating Over an Array
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
}
}
Iterating Over an ArrayList
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Iterating Over a Set
import java.util.HashSet;
import java.util.Set;
public class ForEachExample {
public static void main(String[] args) {
Set<String> animals = new HashSet<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
for (String animal : animals) {
System.out.println(animal);
}
}
}
Important Points to Note:
- Read-Only Access: While iterating a collection using for-each loop, you cannot modify the collection. This is because it gives you read-only access. For this purpose, we use Iterator, an example of this is at the end of this guide.
- Ease to use: It is simple and easier to use than normal for loop as we don’t need counter variable here.
- Performance: There are performance issues in certain cases, for example, if we want to access a particular element from a certain index of ArrayList, then it is not advisable to use for-each loop.
Limitations of for-each loop
- No Access to Index: Although it provides an easy way to iterate, it has certain limitations. For example, If you need the index of the current element, you cannot directly get it using the for-each loop. In such conditions, you would need to use a traditional for loop.
- Modification: As discussed earlier in “read-only access” section that you cannot modify a collection inside for-each loop during iteration. You would need to use Iterator, see the following example:
Modifying a Collection while iterating
To modify a collection during iteration, you would need to use Iterator as shown below. In the following example, we are removing an element from the list inside while loop.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ModifyExample {
public static void main(String[] args) {
List<String> items = new ArrayList<>();
items.add("AA");
items.add("BB");
items.add("CC");
Iterator<String> iterator = items.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
// Checking if the current element is "BB"
// and removing it if it matches
if (item.equals("BB")) {
iterator.remove();
}
}
System.out.println(items); // Output: [A, C]
}
}
Advantages of for-each loop:
- It improves code readability, which reduces the chances of errors during iteration.
- It takes care of the type-safety while iterating as it ensures that the type of element matches with the type of collection you want to iterate over.