In Java, for-each
is a special form of the for
loop designed to iterate over collections, arrays, or any Iterable
objects. It is also known as the enhanced for loop.
🔹 Syntax of for-each Loop
for (datatype variable : collection) {
// body of loop
}
-
datatype
: The type of elements in the collection or array. -
variable
: A temporary variable that holds the current element during each iteration. -
collection
: The array or collection to iterate over.
🔹 for-each with Arrays
public class ForEachArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
}
}
✅ Output:
10
20
30
40
🔹 for-each with List
import java.util.*;
public class ForEachListExample {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
✅ Output:
Apple
Banana
Cherry
🔹 for-each with Set
import java.util.*;
public class ForEachSetExample {
public static void main(String[] args) {
Set<String> colors = new HashSet<>(Arrays.asList("Red", "Green", "Blue"));
for (String color : colors) {
System.out.println(color);
}
}
}
🔹 for-each with Map (Indirectly)
Since a Map
is not directly iterable with for-each, you use one of its views like entrySet()
, keySet()
, or values()
.
import java.util.*;
public class ForEachMapExample {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
// Iterating over entry set (key-value pairs)
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
🔹 Limitations of for-each
Limitation | Description |
---|---|
Cannot modify structure | You can't use remove() directly during iteration. Use iterator instead. |
No index access | Unlike traditional for loops, you don't get the index. |
Forward-only | It only iterates in forward direction. |
🔹 When to Use for-each?
Use it when:
- You want to read/access every element in a collection.
- You don't need the index.
- You don’t need to remove or replace elements.
🔹 Example: Comparing Traditional vs for-each
String[] names = {"Alice", "Bob", "Charlie"};
// Traditional for loop
for (int i = 0; i < names.length; i++) {
System.out.println("Name at index " + i + ": " + names[i]);
}
// Enhanced for-each loop
for (String name : names) {
System.out.println("Name: " + name);
}
Would you like a use-case involving a custom class or nested collections with for-each?
Top comments (0)