Iterable Interface in Java
The Iterable interface in Java is the top interface of the collection hierarchy. It is used to make an object usable in a for-each loop. Any class that implements Iterable promises that it can hand out its elements one by one. In this lesson, you will learn its methods, how the for-each loop uses it, and how to make your own class iterable.
Declaration and Methods
public interface Iterable<T>| Method | Description |
|---|---|
Iterator<T> iterator() | It returns an iterator over the elements. This is the only abstract method. |
default void forEach(Consumer<? super T> action) | It performs the given action for each element. |
default Spliterator<T> spliterator() | It returns a spliterator, used by streams. |
Iterable is in the java.lang package, not java.util, because the for-each loop is part of the language itself.
How the For-Each Loop Uses Iterable
When you write a for-each loop over a collection, the compiler turns it into code that calls iterator():
for (String name : names) { // you write this
System.out.println(name);
}
Iterator<String> it = names.iterator(); // the compiler generates this
while (it.hasNext()) {
String name = it.next();
System.out.println(name);
}So any object that implements Iterable can be used in a for-each loop, not only Java's own collections.
Example: Making Your Own Class Iterable
Let's see an example of a Classroom class that can be used in a for-each loop.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Classroom implements Iterable<String> {
private final List<String> students = new ArrayList<>();
void join(String name) {
students.add(name);
}
@Override
public Iterator<String> iterator() {
return students.iterator();
}
public static void main(String[] args) {
Classroom room = new Classroom();
room.join("Navika");
room.join("Srihitha");
room.join("Advitha");
for (String s : room) {
System.out.println("Present: " + s);
}
room.forEach(s -> System.out.print(s.charAt(0) + " "));
System.out.println();
}
}Present: Navika
Present: Srihitha
Present: Advitha
N S AExplanation: Classroom implements Iterable<String> and returns its list's iterator from iterator(). Because of that, for (String s : room) works directly on a Classroom object. The default method forEach is also available; here it prints the first letter of each name.
Common Mistakes
Trying to use for-each on an object that doesn't implement Iterable. The compiler reports "for-each not applicable to expression type".
Returning the internal list itself instead of an iterator. Return list.iterator() so callers can't replace the list.
Thinking Iterable is in java.util. It's in java.lang.
Practice
- Easy: Make a
Playlistclass that holds song titles and implementsIterable<String>, then loop over it. - Harder: Write a
Rangeclass that implementsIterable<Integer>and produces the numbers from a start to an end without storing them in a list.
Key Takeaways
Was this tutorial helpful?