Java Reference ยท Keywords and Statements
The enhanced for (for-each) statement
Reference for the Java for-each loop: iterating arrays, Lists, Sets and Maps, the Iterable requirement, ConcurrentModificationException and pitfalls.
The enhanced for statement, usually called the for-each loop, visits every element of an array or of any object that implements Iterable. You get each element in a variable and no index to manage, which removes a whole class of off-by-one mistakes.
For arrays the compiler generates an index loop. For an Iterable it calls iterator() and then hasNext() and next(). Because of this, the loop variable is a copy of the element reference, and changing the collection during iteration is restricted.
for (String name : names) { System.out.println(name); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
for (Type variable : arrayOrIterable) { body }
| Part | Description |
|---|---|
Type variable |
Declared in the header. Can be final, can be var. The element type must be assignable to Type (unboxing and widening apply). |
arrayOrIterable |
An array, or an object whose type implements java.lang.Iterable<T>. |
Usage notes
- No index. If you need the position, use the classic
forloop, or keep a separate counter. - Assignments to the variable are local. The loop variable is a fresh variable per iteration; assigning to it does not modify the array or collection. Calling mutating methods on the element object does.
- Fail-fast iterators: adding or removing elements of an
ArrayList,HashMapand similar collections while iterating throwsConcurrentModificationException(on a best-effort basis). UseIterator.remove(),removeIf(), or iterate over a copy. Concurrent collections have weakly consistent iterators instead. null: anullarray orIterablethrowsNullPointerException. Collections that containnullelements pass them to the variable, so unboxing anullinto anintfails.- Maps are not
Iterable. Loop overentrySet(),keySet()orvalues().HashMaporder is unspecified; useTreeMaporLinkedHashMapfor predictable order. - Arrays of arrays: nest two loops; the outer variable has type
int[]. - Primitive streams and
forEachare alternatives, but the for-each loop allowsbreak,continue,returnand checked exceptions. - Custom types become loopable by implementing
Iterable<T>.