The Enhanced <code>for</code> Loop (for-each) in Java
The enhanced for β also called for-each β iterates every element of an array or Iterable without tracking an index. It's the cleanest way to read through a collection when you only need the elements.
Syntax
for (ElementType name : iterable) {
// use name
}
// Examples
for (String s : names) System.out.println(s);
for (int n : new int[]{1, 2, 3}) sum += n;
for (Map.Entry<String,Integer> e : map.entrySet()) { ... }
Works with anything Iterable
Any class that implements Iterable<T> or is an array. Map isn't Iterable β iterate entrySet(), keySet() or values() instead.
Limitations
- No index β if you need
i, use a classicfor. - No modification β calling
list.remove(x)orlist.add(x)inside throwsConcurrentModificationException. UseremoveIfor an explicitIterator. - No
nextpeeking β you can't look at the next element without anIterator.
Under the hood
for (User u : list) { send(u); }
// Is equivalent to:
for (Iterator<User> it = list.iterator(); it.hasNext(); ) {
User u = it.next();
send(u);
}
forEach method (Java 8+)
list.forEach(System.out::println); // a method, not a loop
list.forEach(user -> send(user));
Convenient with method references, but you can't break or return from inside. For complex iteration, prefer the for-each loop.
Common mistakes
- Trying to remove during iteration β use
removeIf. - Needing the index anyway β either keep a counter outside or switch to classic
for. - Iterating a
Mapdirectly β iteratemap.entrySet(),map.keySet()ormap.values().
Related
Pillar: Java control flow. See also for loop, Iterator.