ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Iterable
Book 1 · Volume II — Generics, Collections & Type System · Topic 6.2

Iterable

Iterable and the enhanced for loop

12 min readStage 1 · Foundations14 interview questions
Prerequisites
6.1 Iterator
Covers
Iterable · Enhanced for loop
Related
6.3 Spliterator · B1V1 2.5 Control Flow
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

java.lang.Iterable<T> is the interface for anything that can produce an Iterator<T>. Implementing it makes a type usable in the enhanced for loop (for-each). Collection extends Iterable, so every collection qualifies; custom types — ranges, paginated results, tree structures — can implement it too.

2Why It Exists

Until Java 5, walking a collection meant writing the iterator loop by hand: call iterator(), test hasNext(), call next() and cast the result, because collections held Object. Java 5 added generics and the enhanced for loop together, and the loop needed a contract that said "this can be traversed" without saying anything else. java.lang.Iterable is that contract. It lives in java.lang, not java.util, because the language itself depends on it.

Separating "can be traversed" from "is a collection" matters for API design. A sequence of database pages, the lines of a log, the nodes of a tree or a numeric range has no useful size() or contains() and may be too large to hold in memory, yet callers should still be able to write for (Customer c : customers). Implementing one method, iterator(), gives such a type the loop, forEach and, through spliterator(), streams.

3Core Concepts

Iterable

Iterable declares one abstract method, iterator(), and two defaults: forEach(Consumer<? super T>) and spliterator(). Each call to iterator() should return a new, independent iterator so that a value can be traversed more than once. Being an Iterable is a lighter promise than being a Collection: no size, no contains, no mutation — useful for lazily computed or very large sequences.

Enhanced for loop

for (T x : expr) works on arrays and Iterables. For an Iterable it compiles to an iterator loop; for an array, to an indexed loop, with no iterator allocated. The loop variable is a copy of each element reference, so assigning to it does not change the collection, and there is no index or remove operation — use an explicit iterator or indexed loop for those.

Enhanced for loops over an Iterable and over an array, as compiled
Figure 1 — Enhanced for loops over an Iterable and over an array, as compiled

4How It Works Internally

The enhanced for loop is resolved entirely by the compiler; the bytecode contains no special instruction for it. The Java Language Specification (14.14.2) defines the translation. For an Iterable, for (T x : expr) body becomes for (Iterator<T> i = expr.iterator(); i.hasNext(); ) { T x = i.next(); body }, with a cast where generics require one. For an array, it becomes an indexed loop over a temporary copy of the array reference: T[] a = expr; for (int i = 0; i < a.length; i++) { T x = a[i]; body }. In both cases expr is evaluated once, before the first iteration; if it is null, the loop throws NullPointerException at once (Example 3).

Iterable's two default methods are built on iterator() (Figure 2). forEach(action) is simply a for-each loop over this that calls the action for each element; collections such as ArrayList override it with a faster loop over their array. spliterator() wraps iterator() in Spliterators.spliteratorUnknownSize(iterator(), 0): it reports no size and no characteristics, and it can split only by copying batches of elements into arrays. A sequential stream over it works well; a parallel one gains little (6.3). Collection overrides spliterator() to report SIZED, and the concrete collections report more.

One iterator() method gives a type the loop, forEach and a spliterator
Figure 2 — One iterator() method gives a type the loop, forEach and a spliterator

5APIs / Features / Syntax

The API is small. These are the members of Iterable and the helpers that connect it to the rest of the platform:

Member or helperSincePurpose
Iterator<T> iterator()Java 5The one abstract method; return a new, independent iterator
default void forEach(Consumer<? super T>)Java 8Internal iteration; override for speed
default Spliterator<T> spliterator()Java 8Unknown size, no characteristics; override for parallel streams
StreamSupport.stream(spliterator, parallel)Java 8Turn any Iterable into a Stream
for (var x : iterable)Java 10Loop variable type inferred from the element type
SequencedCollection.reversed()Java 21for (T x : list.reversed()) walks a list backwards

Iterable is not annotated @FunctionalInterface, but it has exactly one abstract method, so a lambda can implement it: Iterable<String> it = () -> source.iterator();. That is convenient for adapting an existing iterator to a for-each loop, and dangerous if the lambda returns the same iterator every time (Example 2).

6Practical Examples

Example 1 — A lazily paginated Iterable

Problem. A batch job processes every customer of a remote API that returns results 100 at a time. Loading all pages into one list first would hold every customer in memory; the job should fetch the next page only when the previous one is used up.

JAVAA lazily paginated Iterable
// Custom Iterable: walk pages of results lazily
public final class Pages<T> implements Iterable<T> {
    private final Function<Integer, List<T>> fetchPage;
    public Pages(Function<Integer, List<T>> fetchPage) { this.fetchPage = fetchPage; }

    public Iterator<T> iterator() {
        return new Iterator<>() {
            int page = 0; Iterator<T> current = fetchPage.apply(0).iterator();
            public boolean hasNext() {
                while (!current.hasNext()) {
                    List<T> next = fetchPage.apply(++page);
                    if (next.isEmpty()) return false;
                    current = next.iterator();
                }
                return true;
            }
            public T next() {
                if (!hasNext()) throw new NoSuchElementException();
                return current.next();
            }
        };
    }
}
for (Customer c : new Pages<>(p -> api.customers(p, 100))) process(c);

Why it works. The iterator holds only the current page. hasNext() fetches the next page when the current one is exhausted and reports the end when an empty page arrives, so next() stays simple. For 250 customers the kit's version of this loop makes four page calls: three full or partial pages and one empty page that ends the walk. Each iterator() call starts again from page 0, which makes the type re-iterable but also means that every new loop repeats the remote calls (section 8).

Example 2 — Mini program: one Iterable type for for-each, forEach and streams

Problem. Reports need numeric ranges with a step, such as every second day or every tenth row, usable in loops and in streams, without allocating a list of numbers. The program also shows the most common Iterable bug.

JAVARangeDemo.java
public class RangeDemo {
    /** from, from + step, ... below to; stores no elements. */
    record Range(int from, int to, int step) implements Iterable<Integer> {
        Range {
            if (step <= 0) throw new IllegalArgumentException("step " + step);
        }
        @Override public Iterator<Integer> iterator() {  // new cursor
            return new Iterator<>() {
                int next = from;
                public boolean hasNext() { return next < to; }
                public Integer next() {
                    if (!hasNext()) throw new NoSuchElementException();
                    int v = next; next += step; return v;
                }
            };
        }
    }
 
    public static void main(String[] args) {
        Range evens = new Range(0, 10, 2);
        StringBuilder sb = new StringBuilder();
        for (int n : evens) sb.append(n).append(' ');     // 1. for-each
        System.out.println("for-each: " + sb.toString().trim());
        List<Integer> copy = new ArrayList<>();
        evens.forEach(copy::add);                         // 2. default forEach
        System.out.println("forEach:  " + copy);
        int sum = StreamSupport.stream(evens.spliterator(), false)  // 3. stream
                .mapToInt(Integer::intValue).sum();
        long count = StreamSupport.stream(evens.spliterator(), false)
                .count();
        System.out.println("stream:   sum " + sum + ", count " + count);
 
        Iterator<Integer> shared = evens.iterator();    // 4. one-shot Iterable
        Iterable<Integer> oneShot = () -> shared;
        int first = 0, second = 0;
        for (int n : oneShot) first++;
        for (int n : oneShot) second++;
        System.out.println("one-shot: first loop " + first
                + ", second loop " + second);
    }
}
OUTPUT
for-each: 0 2 4 6 8
forEach:  [0, 2, 4, 6, 8]
stream:   sum 20, count 5
one-shot: first loop 5, second loop 0

Why it behaves this way. Range stores three numbers, not five elements. Every call to iterator() returns a new cursor, so the for-each loop, forEach and the two streams each walk the whole range; count gives 5 because the default spliterator knows no size and has to traverse. The lambda in step 4 compiles because Iterable has a single abstract method, but it returns the same iterator to every loop: the first loop exhausts it and the second finds nothing, without any error.

Example 3 — What the compiler generates for for-each

Problem. Section 3 says the loop variable is a copy and that for-each has no index. This program checks the consequences of the translation in section 4 on arrays, lists of mutable objects, maps and null.

JAVAForEachDesugar.java
public class ForEachDesugar {
    public static void main(String[] args) {
        int[] prices = {100, 250, 75};
        for (int p : prices) p = p * 2;              // changes the copy only
        System.out.println("after for-each: " + Arrays.toString(prices));
        for (int i = 0; i < prices.length; i++) prices[i] *= 2;   // real update
        System.out.println("after index loop: " + Arrays.toString(prices));
 
        List<StringBuilder> names = List.of(new StringBuilder("ann"),
                new StringBuilder("raj"));
        for (StringBuilder n : names) n.append('!');  // same objects: visible
        System.out.println("mutated elements: " + names);
 
        Map<String, Integer> stock = new TreeMap<>(Map.of("pen", 3, "ink", 0));
        for (Map.Entry<String, Integer> e : stock.entrySet())  // not the Map
            System.out.println("  " + e.getKey() + " -> " + e.getValue());
 
        List<String> missing = null;
        try {
            for (String s : missing) System.out.println(s);
        } catch (NullPointerException e) {
            System.out.println("null Iterable: NullPointerException");
        }
    }
}
OUTPUT
after for-each: [100, 250, 75]
after index loop: [200, 500, 150]
mutated elements: [ann!, raj!]
  ink -> 0
  pen -> 3
null Iterable: NullPointerException

Why it behaves this way. p is a local variable that receives a copy of each array element, so doubling it changes nothing; only the indexed loop writes back. The list loop also receives copies, but copies of references: append changes the objects themselves, which the list still holds. A Map is not an Iterable, so the loop runs over entrySet(), in key order because the map is a TreeMap. The null list fails at the hidden missing.iterator() call, before any element is processed.

Example 4 — An Iterable tree walked without recursion

Problem. A site navigation menu is a tree. Callers want for (Node n : site) to visit every node in display order, and the tree may be deep enough that recursive traversal is not wanted.

JAVATreeWalk.java
public class TreeWalk {
    record Node(String name, List<Node> children) implements Iterable<Node> {
        Node(String name, Node... children) { this(name, List.of(children)); }
 
        @Override public Iterator<Node> iterator() {    // pre-order
            Deque<Node> stack = new ArrayDeque<>(List.of(this));
            return new Iterator<>() {
                public boolean hasNext() { return !stack.isEmpty(); }
                public Node next() {
                    Node n = stack.pop();       // empty: NoSuchElement
                    for (int i = n.children.size() - 1; i >= 0; i--)
                        stack.push(n.children.get(i));  // leftmost on top
                    return n;
                }
            };
        }
    }
 
    public static void main(String[] args) {
        Node site = new Node("shop",
                new Node("catalog", new Node("books"), new Node("music")),
                new Node("checkout", new Node("cart"), new Node("payment")));
        List<String> order = new ArrayList<>();
        for (Node n : site) order.add(n.name());
        System.out.println(order);
        long leaves = 0;
        for (Node n : site) if (n.children().isEmpty()) leaves++;
        System.out.println("leaves: " + leaves);
    }
}
OUTPUT
[shop, catalog, books, music, checkout, cart, payment]
leaves: 4

Why it behaves this way. The iterator keeps an explicit stack instead of the call stack. next() pops a node and pushes its children in reverse, so the leftmost child is on top and the walk is pre-order: a parent, then its subtrees from left to right. Each iterator() call creates a new stack, so the second loop, which counts the leaves, walks the whole tree again. An empty stack makes pop() throw NoSuchElementException, which is what the contract requires.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
iterator() returns the same Iterator object every timeThe second loop over the value finds nothing, silently (Example 2)Create a new iterator in every iterator() call
Assigning to the loop variable to update elementsOnly the local copy changes; the array or list is unchangedUse an indexed loop, ListIterator.set or List.replaceAll
Calling collection.remove inside for-eachConcurrentModificationException, or a silently skipped element (6.1)removeIf, or an explicit iterator and it.remove()
Looping over a value that may be nullNullPointerException from the hidden iterator() callReturn empty collections instead of null
Iterating a lazy Iterable twice (once to count, once to process)Every expensive step, such as a remote page call, runs twiceTraverse once, or copy into a List when two passes are needed
An Iterable over an open resource (file, cursor) with no closeCallers that stop early leak the file handle or the connectionReturn a Stream with onClose and document try-with-resources

8Performance & Production Considerations

A for-each loop over an array allocates nothing and compiles to the same code as an indexed loop. Over a collection it allocates one iterator per loop; for short-lived loops the JIT usually removes that allocation through escape analysis, so the choice between for-each and an indexed loop over an ArrayList rarely matters. Boxing matters more: an Iterable<Integer> produces an Integer object for each value outside the small cached range, which is why number-heavy code uses int[] or IntStream.

The real production risks are in lazy implementations. A paginated or I/O-backed Iterable does its expensive work inside hasNext() or next(), so every traversal repeats it, and code that looks like a cheap loop can issue hundreds of remote calls. Log or meter the underlying calls, document that the type is lazy, and avoid default spliterators where parallel streams are expected: override spliterator() when the source can report its size or split cheaply.

9Architecture & Design Considerations

Iterable is the weakest useful promise an API can make about a sequence: callers may traverse it, and nothing else. That weakness is its strength at module boundaries, because the implementation stays free to compute elements lazily, page through a remote system or change its storage. Choose the return type by what callers need and what the implementation must keep free (Figure 3).

What each return type promises the caller
Figure 3 — What each return type promises the caller

A domain object that exposes its children only as an Iterable keeps control over them: callers cannot add or remove through it, although the returned iterator's remove() must still be blocked. When a sequence holds a resource, such as a file, a database cursor or a network stream, Iterable is the wrong type, because a for-each loop has no way to close it; a Stream used in try-with-resources, or a callback that receives each element, puts the lifetime under the owner's control.

10Interview Questions & Answers

Q1L1 · BasicConcept

What must a class implement to be used in a for-each loop?

java.lang.Iterable<T>, providing iterator(). Arrays work in for-each without implementing anything.

Q2L2 · IntermediateInternals

What does the enhanced for loop compile to?

For an Iterable, a loop calling iterator(), hasNext() and next(); for an array, an indexed loop over its length.

Q3L3 · Senior EngineerTricky

Why can't you remove elements inside a for-each loop?

The loop hides the iterator, so you can only call the collection's remove, which modifies it behind the iterator's back and triggers ConcurrentModificationException.

Q4L3 · Senior EngineerTrade-off

When would you expose Iterable rather than List or Stream from an API?

When results are produced lazily or are very large — pagination, file or cursor reading — and callers only need to traverse, possibly more than once. Iterable promises little, leaving freedom in implementation; Stream is better when callers need pipeline operations and single-use traversal is acceptable.

Q5L1 · BasicConcept

Can you write for (var e : map) for a Map? If not, what do you loop over?

No. Map does not extend Iterable, because a map is a set of key-value pairs rather than a sequence of single elements, so the compiler rejects the loop. Loop over one of its views: entrySet() for keys and values together, keySet() or values(). map.forEach((k, v) -> ...) is the internal-iteration alternative.

Q6L2 · IntermediateCode

What does this program print?

JAVAReassignQuiz.java
public class ReassignQuiz {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("ann", "raj"));
        for (String s : names) s = s.toUpperCase();
        int[] qty = {1, 2};
        for (int q : qty) q++;
        System.out.println(names + " " + Arrays.toString(qty));
    }
}

It prints [ann, raj] [1, 2]. In both loops the loop variable is a local copy: for the list a copy of each reference, for the array a copy of each int. s = s.toUpperCase() makes the local variable point to a new string and q++ increments the local copy, so neither the list nor the array changes. names.replaceAll(String::toUpperCase) and an indexed loop over qty would update them.

Q7L3 · Senior EngineerCode

What does this program print?

JAVAOneShotQuiz.java
public class OneShotQuiz {
    public static void main(String[] args) {
        Iterator<String> it = List.of("a", "b", "c").iterator();
        Iterable<String> lines = () -> it;
        int n = 0;
        for (String s : lines) n++;
        for (String s : lines) n++;
        System.out.println(n);
    }
}

It prints 3, not 6. The lambda is a valid Iterable, but each call to iterator() returns the same iterator, so the first loop exhausts it and the second loop's first hasNext() returns false. Nothing fails, which is what makes the bug dangerous; iterator() must create a new iterator on every call (Example 2).

Q8L3 · Senior EngineerInternals

What does Iterable.spliterator() return by default, and why does it matter?

It returns Spliterators.spliteratorUnknownSize(iterator(), 0): a spliterator with no size estimate and no characteristics, which splits only by copying batches of elements into arrays. Sequential streams over it work normally, but operations cannot use a known size, and a parallel stream gets poorly balanced work (6.3). A custom Iterable that backs parallel or size-sensitive streams should override spliterator(), for example with Spliterators.spliterator(iterator(), size, ORDERED) when the size is known.

Q9L3 · Senior EngineerTricky

Iterable is not annotated @FunctionalInterface. Can you still implement it with a lambda, and is it a good idea?

Yes. A lambda can implement any interface with exactly one abstract method, and the annotation only asks the compiler to check that; Iterable has one abstract method, iterator(). for (String s : (Iterable<String>) stream::iterator) is a known idiom for looping over a stream. It is safe only when the lambda creates a new iterator on each call, as source::iterator on a collection does; capturing one existing iterator or a stream gives an Iterable that works once and then appears empty or throws IllegalStateException.

Q10L3 · Senior EngineerScenario

A nightly export that reads customers through a paginated Iterable now takes twice as long and the API provider reports double the call volume. The only recent change added a line that logs how many customers will be exported. What happened?

The new line almost certainly traverses the Iterable to count it, for example with a loop or StreamSupport.stream(...).count(), before the export traverses it again. Because the Iterable is lazy and each iterator() call starts from page 0, every page is fetched twice. Count during the single export pass and log the total at the end, or ask the API for the total if it reports one; also add a metric for page calls so such regressions show up immediately.

Q11L4 · Technical ArchitectDesign

Design an API for reading millions of rows from a database cursor so that callers cannot leak the connection.

Do not return an Iterable or Iterator: a caller that stops early or throws leaves the cursor open. Either return a Stream<Row> whose onClose closes the cursor and statement, and document that it must be used in try-with-resources, or invert control with a method such as void forEachRow(Consumer<Row> action) that opens, iterates and closes inside a finally. The callback version cannot leak at all; the Stream version composes with the rest of the stream API. Fetch in batches (a JDBC fetch size) in both.

Q12L4 · Technical ArchitectTrade-off

When do you prefer external iteration (for-each) over internal iteration (forEach or streams)?

External iteration keeps control in the caller: break and return work, checked exceptions can be thrown, local variables can be updated, and a debugger steps through it naturally. Internal iteration lets the collection choose how to traverse, which ArrayList.forEach uses for a tighter loop and streams use for laziness and parallelism, and it reads well for short transformations. Use for-each for loops with early exit, checked exceptions or complex state, and forEach or a stream for simple actions and pipelines.

Q13L5 · Solution ArchitectDesign

Your platform team builds an SDK used by thirty teams to read a paginated partner API. Which traversal abstraction do you expose, and why?

Expose a typed page-level call for teams that need control (Page<T> fetch(cursor) with the next cursor) and one convenience method that hides paging, returning a lazy Stream<T> that fetches pages on demand and closes resources in onClose. A Stream makes the single pass explicit, avoids the accidental double traversal of a lazy Iterable, and lets teams stop early with limit or takeWhile. Build in rate limiting, retries and a metric per page call, and document that results are not cached.

Q14L5 · Solution ArchitectTrade-off

An Order aggregate has many order lines. Should it expose them as List, Iterable or a copy, and what does each choice cost?

Returning the internal List is convenient but lets callers change the aggregate without its rules. Returning an Iterable hides the list type but still needs a remove() that throws, and callers lose size() and get(i). An immutable copy or an unmodifiable view, List.copyOf(lines) or Collections.unmodifiableList(lines), gives callers a full read API and keeps all changes inside methods such as addLine, at the cost of a copy or of a view that reflects later changes (7.1). For most aggregates an immutable list is the best balance (7.2).

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Iterable provides iterator(), forEach and spliterator().
  • for-each works on Iterables and arrays; it hides the iterator.
  • Return a fresh iterator on each call; use Iterable for lazy sequences.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.