Iterable
The interface of everything that a for-each loop can iterate over.
Available since: Java 1.5
Syntax
public interface Iterable<T> {
Iterator<T> iterator();
default void forEach(Consumer<? super T> action);
}Examples
The for-each loop and the forEach() method:
void main() {
List<String> langs = List.of("Java", "Kotlin", "Scala");
for (String lang : langs) {
IO.println(lang);
}
langs.forEach(lang -> IO.println(lang.length()));
}Output:
Java
Kotlin
Scala
4
6
5Your own class in a for-each loop:
record Countdown(int from) implements Iterable<Integer> {
public Iterator<Integer> iterator() {
return new Iterator<>() {
int current = from;
public boolean hasNext() { return current > 0; }
public Integer next() { return current--; }
};
}
}
void main() {
for (int n : new Countdown(3)) {
IO.println(n);
}
}Output:
3
2
1Notes
The for (T x : collection) loop works with arrays and any Iterable: all collections except Map (for a map iterate over entrySet(), keySet() or values()). Removing collection elements inside such a loop is not allowed — it causes ConcurrentModificationException; use removeIf() or Iterator.remove().
See also
- Iterator — An object that hands out collection elements one by one.
- Map.forEach() — Runs an action for every pair of a map.
- Stream.forEach() — Runs an action for every stream element (a terminal operation).
Related recipes
In the tutorial
- Iterating over collections — How to go through a collection in Java: the for-each loop, indexes, forEach with a lambda, iterating a map, Iterator and removeIf.