Java Reference ยท java.lang
The Iterable interface
Reference for java.lang.Iterable: implement iterator() to make any class usable in the for-each loop, plus forEach() and spliterator() explained.
java.lang.Iterable<T> is the interface that makes an object usable as the target of an enhanced for loop. It has a single abstract method, iterator(), which returns a fresh Iterator<T> positioned before the first element. Every Collection is an Iterable; arrays are not, even though the for-each loop accepts them as a special case.
If your class holds a sequence of things (a deck of cards, a range of numbers, the rows of a result), implement Iterable and callers get the for-each loop, forEach(), and an easy way to stream the elements, all from one method.
public interface Iterable<T> { Iterator<T> iterator(); default void forEach(Consumer<? super T> action) { ... } default Spliterator<T> spliterator() { ... } }
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
public interface Iterable<T>
| Method | Description |
|---|---|
Iterator<T> iterator() |
Abstract. Returns a new iterator over the elements. |
default void forEach(Consumer<? super T> action) |
Calls action for each element in iteration order (since Java 8). Throws NullPointerException if action is null. |
default Spliterator<T> spliterator() |
A spliterator built from the iterator, with unknown size (since Java 8). Collections override it with better ones. |
Usage notes
- The for-each loop calls
iterator()once and thenhasNext()andnext()repeatedly. It never callsremove(). - Return a new iterator each time. If
iterator()hands back the same object, a second loop over the sameIterablefinds it already exhausted. - Fail clearly at the end.
next()should throwNoSuchElementExceptionwhen there is nothing left, not returnnull. - No
stream()onIterable. OnlyCollectionhas it. UseStreamSupport.stream(iterable.spliterator(), false), or implementCollectionif you need more than iteration. remove()is optional. The default throwsUnsupportedOperationException; implement it only if removal makes sense, and remember theConcurrentModificationExceptionconvention for fail-fast iterators.- Infinite sequences are allowed. An
Iterablecan be unbounded, but thenforEachnever returns, so document it. - Use a generic-friendly name in APIs: accepting
Iterable<? extends T>instead ofList<T>makes a method work with sets, queues and custom types alike.