Enhanced for-each
IntermediateThe cleanest loop syntax in Java — works on arrays and any Iterable with no index boilerplate, and how it compares to classic for and Iterator.
Overview
The enhanced for-each (for (T item : collection)) is syntactic sugar for an explicit Iterator. For arrays it compiles to a classic index-based loop. It is the preferred iteration style when you do not need the index, do not need to modify the collection during iteration, and do not need bi-directional traversal. Understanding what it compiles to helps you know when it is not applicable.
Syntax & Compilation
For arrays the compiler generates: for (int i=0; i<arr.length; i++). For Iterable it generates: Iterator it=col.iterator(); while(it.hasNext()) { T item=it.next(); ... }. You cannot call it.remove() inside a for-each — use removeIf() or an explicit iterator loop instead.
import java.util.*;
public class ForEachDemo {
public static void main(String[] args) {
// Array — compiles to index loop
int[] nums = {1, 2, 3, 4, 5};
int sum = 0;
for (int n : nums) sum += n;
System.out.println(sum); // 15
// Collection — compiles to iterator
List<String> names = List.of("Alice", "Bob", "Carol");
for (String name : names) System.out.print(name + " ");
System.out.println();
// Map — iterate entrySet
Map<String, Integer> scores = Map.of("Alice", 90, "Bob", 85);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// 2D array
int[][] matrix = {{1,2},{3,4},{5,6}};
for (int[] row : matrix) {
for (int val : row) System.out.print(val + " ");
}
System.out.println();
// Custom Iterable — see Iterator topic
// for (int n : new Range(1, 5)) System.out.print(n + " ");
}
}When NOT to Use for-each
Avoid for-each when you need the index, need to remove elements, need to replace elements in-place, need reverse/skip traversal, or need to iterate two collections in sync. In those cases fall back to classic for or explicit iterator.
import java.util.*;
public class ForEachLimits {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1,2,3,4,5));
// Need index — use classic for
for (int i = 0; i < list.size(); i++) {
if (i % 2 == 0) list.set(i, list.get(i) * 10);
}
System.out.println(list); // [10, 2, 30, 4, 50]
// Need removal — use removeIf (cleanest)
list.removeIf(n -> n < 10);
System.out.println(list); // [10, 30, 50]
// Iterate two lists in sync — classic for
List<String> keys = List.of("a","b","c");
List<Integer> vals = List.of(1, 2, 3);
for (int i = 0; i < keys.size(); i++) {
System.out.println(keys.get(i) + "=" + vals.get(i));
}
// forEach method (Java 8+) with lambda — cleaner than for-each in some cases
list.forEach(n -> System.out.print(n + " "));
System.out.println();
}
}forEach() Method vs Enhanced for-each
Iterable.forEach(Consumer) (Java 8+) is a method that takes a lambda. It is functionally equivalent to the enhanced for-each but enables method references and fits naturally into fluent API chains. The enhanced for-each keyword is better when you need break/continue; forEach() does not support those.
import java.util.*;
import java.util.stream.*;
public class ForEachMethod {
public static void main(String[] args) {
List<String> names = List.of("Alice","Bob","Carol");
// Enhanced for-each — supports break/continue
for (String name : names) {
if (name.equals("Bob")) break; // stop early
System.out.print(name + " ");
}
System.out.println(); // Alice
// forEach method — cannot break, but clean for side effects
names.forEach(System.out::println);
// forEach with complex lambda
Map<String, Integer> scores = new LinkedHashMap<>(
Map.of("Alice",90,"Bob",85,"Carol",92));
scores.forEach((name, score) ->
System.out.printf("%-8s %d%n", name, score));
// forEach on stream — terminal operation
names.stream()
.filter(n -> n.length() > 3)
.map(String::toUpperCase)
.forEach(System.out::println); // ALICE CAROL
}
}Key Points to Remember
- Enhanced for-each compiles to an iterator loop for Iterable; index loop for arrays
- Cannot remove elements inside for-each — use removeIf() or an explicit Iterator
- Cannot access the index, iterate in reverse, or skip elements with for-each
- Iterable.forEach(lambda) supports method references but cannot use break/continue
- For Map, iterate entrySet() with for-each to get both key and value simultaneously
- Two collections in sync require a classic index-based for loop
Practice Enhanced for-each in the Playground
Run and modify code directly in your browser - no setup needed.
Interview Questions
Sign in to ask AriaWhat does the enhanced for-each compile to for arrays vs collections?
Can you remove an element from a list inside a for-each loop?
What is the difference between for-each and forEach() method?
What interface must a class implement to be used in a for-each loop?
When would you prefer a classic for loop over the enhanced for-each?
Ask Aria about Enhanced for-each
Your personal AI tutor — ask anything about this concept