Iterable Interface in Java

Naveen AnamaneniUpdated · 3 min read
mediumJava 25javacollections

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

Declaration
public interface Iterable<T>
MethodDescription
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():

What the compiler writes
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.

Classroom.java▶ Try it
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();
    }
}
Output
Present: Navika
Present: Srihitha
Present: Advitha
N S A

Explanation: 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

  1. Easy: Make a Playlist class that holds song titles and implements Iterable<String>, then loop over it.
  2. Harder: Write a Range class that implements Iterable<Integer> and produces the numbers from a start to an end without storing them in a list.

Quick check: Iterable

4 questions
1Which method must a class implement for Iterable?
2Which package is Iterable in?
3What does a for-each loop call behind the scenes?
4Can your own class be used in a for-each loop?

Key Takeaways

Was this tutorial helpful?

Lesson 254 of 482