# IteratorA playlist changes how it stores songs and twelve loops break. Learn how an iterator hides a collection's insides, how to remove safely while looping, how to page an API, and when streams fit better.

The playlist class in a music app changed how it stores songs. And twelve loops across the app
stopped compiling. The songs used to sit in an array. Now they're a chain of nodes, so moving a song
is cheap. Every loop broke, and none of them cared how songs were stored. They only wanted the next
one. So why does every loop know how songs are stored? The **Iterator** pattern is the answer, and you
use it every day.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows
it section by section, with diagrams and a little extra depth.

{{< lesson-video youtube="Hw9XDY6Gxt8" title="Iterator" >}}

## Twelve loops that only wanted the next song

```mermaid {alt="Twelve parts of the music app (player, shuffle, export, search and others) each loop over the playlist's array directly. When the playlist switches to a chain of nodes, every one of them breaks." caption="Callers that reach into a collection break when its insides change."}
flowchart LR
  P["player"] --> A["Playlist's array"]
  S["shuffle"] --> A
  E["export"] --> A
  M["… nine more loops"] --> A
  A -->|"becomes a chain of nodes"| X["every loop breaks"]
  class P,S,E,M c4
  class A c1
  class X bad
```

## The audio guide

Think of a museum audio guide. You press next, and you hear about the next exhibit. You never need the
floor plan. The museum can move its rooms around, and the guide still walks you through. You press
next, exactly as before. And every visitor has their own guide, each at its own place in the museum.
And if staff move a painting while you're mid-route, a careful guide stops, and tells you the route is
out of date. Remember that one.

In the pattern's words, the museum is the **collection** (GoF: the aggregate), and the guide is the
**iterator**. It asks two questions: is there more (`hasNext()`)? And: what's next (`next()`)?

```mermaid {alt="The audio guide mapped onto code: the museum is the collection (Playlist); the guide is the iterator; the question 'is there more?' is hasNext(); pressing next is next()." caption="The guide knows the route; you only press next."}
flowchart LR
  A["museum"] --> A2["collection: Playlist"]
  B["audio guide"] --> B2["iterator"]
  C["is there more?"] --> C2["hasNext()"]
  D["next exhibit"] --> D2["next()"]
  class A2 c1
  class B2 c5
```

## The obvious version: hand out the array

Here's where the music app started. The playlist keeps its songs in an array, with a count, and hands
the array out with a getter.

```java
public class Playlist {
    private Song[] songs = new Song[100];
    private int count;

    public Song[] getSongs() { return songs; }
    public int size() { return count; }
}
```

Callers take the array and loop with an index, up to the size.

```java
Song[] songs = playlist.getSongs();
for (int i = 0; i < playlist.size(); i++) {
    play(songs[i]);
}
```

And that's fair. It's direct, it's fast, and every Java developer reads it at a glance. Plenty of small
apps keep this for years.

## Why it breaks

But look at what every caller now knows. The songs are in an array. It's indexed. And only the first
`count` slots are real. Change any of those, a chain of nodes, or songs loaded page by page, and every
loop has to change with it.

And since callers hold the real array, any one of them can write `songs[3] = null;` and break the
playlist for everyone. It's handing every visitor the floor plan. Move one room, and you reprint every
plan.

```mermaid {alt="What every caller of getSongs knows: it's an array, it's indexed, only count slots are real, and it holds the real array so it can write into it. Each of these couples the caller to the playlist's insides." caption="The insides leaked."}
flowchart TD
  G["getSongs() hands out the array"] --> K1["it's an array"]
  G --> K2["it's indexed"]
  G --> K3["only count slots are real"]
  G --> K4["callers can write into it"]
  class G c1
  class K1,K2,K3,K4 bad
```

## The key idea: give the walk its own object

So don't hand out the array. Hand out a small object that walks it for you: an iterator. It answers
two questions. Has next: is there more? And next: give me the next one, and move along.

```java
public interface Iterator<T> {
    boolean hasNext();
    T next();
}
```

(That's the heart of `java.util.Iterator`, simplified: the real interface also has default methods,
`remove` and `forEachRemaining`.) The collection makes a fresh iterator for every walk, and each one
keeps its own place. The Gang of Four state the intent like this: "Provide a way to access the
elements of an aggregate object sequentially without exposing its underlying representation."

> **Walk it. Don't open it.** The iterator keeps your place.

## Building it in Java: Iterable, the iterator, for-each

In Java, the playlist implements `Iterable`. That's one method, `iterator()`, which returns a new
iterator over the array. The iterator keeps an index. `hasNext` checks it against the count. `next`
returns the song and moves on, and throws if nothing is left.

```java
public class Playlist implements Iterable<Song> {
    private Song[] songs = new Song[100];
    private int count;

    public Iterator<Song> iterator() {
        return new Iterator<>() {
            private int i = 0;
            public boolean hasNext() { return i < count; }
            public Song next() {
                if (!hasNext()) throw new NoSuchElementException();
                return songs[i++];
            }
        };
    }
}
```

Now the for-each loop works on a playlist. The compiler turns it into calls to `iterator`, `hasNext`,
and `next` (Java Language Specification, §14.14.2).

```java
for (Song s : playlist) {
    play(s);
}
```

```mermaid {alt="Sequence: the for-each loop calls iterator() on the Playlist once and gets an Iterator; then it repeatedly calls hasNext() and next() on the Iterator until hasNext() returns false." caption="What the compiler turns for-each into."}
sequenceDiagram
  participant L as for-each loop
  participant P as Playlist
  participant I as Iterator
  L->>P: iterator()
  P-->>L: a new Iterator
  loop while hasNext() is true
    L->>I: hasNext()
    L->>I: next()
    I-->>L: the next Song
  end
```

Then switch the playlist to a chain of nodes. Only the iterator method changes: it follows the links
instead of counting.

```java
public Iterator<Song> iterator() {
    return new Iterator<>() {
        private Node node = first;
        public boolean hasNext() { return node != null; }
        public Song next() {
            if (node == null) throw new NoSuchElementException();
            Song s = node.song;
            node = node.next;
            return s;
        }
    };
}
```

And every for-each loop stays exactly as it was. Who creates the iterator is a factory method, by the
way (see [Factory Method](/patterns/factory-method-pattern/), which uses `Iterable.iterator()` as
its example), but here we care about the iterator itself.

```mermaid {alt="Class diagram: Playlist implements Iterable of Song and creates an Iterator of Song; the loop depends only on Iterable and Iterator; the array iterator and the chain iterator both implement Iterator." caption="Callers see Iterable and Iterator; the storage hides behind them."}
classDiagram
  direction LR
  class Iterable {
    <<interface>>
    +iterator() Iterator
  }
  class Iterator {
    <<interface>>
    +hasNext() boolean
    +next() T
  }
  Iterable <|.. Playlist
  Playlist ..> Iterator : creates
  Iterator <|.. ArrayWalk
  Iterator <|.. ChainWalk
  Loop --> Iterable
  Loop --> Iterator
```

(`ArrayWalk` and `ChainWalk` stand for the two anonymous classes above.)

## Several walks at once

Because each call makes a new iterator, two walks can run at the same time. The player is on song
three, while the export is on song seven. The Gang of Four list this as a benefit: "More than one
traversal can be pending on an aggregate."

That's also the line between `Iterable` and `Iterator`. An **iterable** is something you can walk,
again and again. An **iterator** is one walk in progress.

| | `Iterable<T>` | `Iterator<T>` |
|---|---|---|
| What it is | something you can walk | one walk in progress |
| Main method | `iterator()` | `hasNext()`, `next()` |
| How many | one collection | as many as there are walks |
| Keeps a place? | no | yes |

## Removing while you walk

A common belief is that removing from a list inside a for-each loop is fine, if you're careful. Here's
the loop that removes skipped songs.

```java
for (Song s : songs) {                    // songs: an ArrayList<Song>
    if (s.isSkipped()) songs.remove(s);   // the list changes behind the iterator
}
```

The list changes, but the loop's iterator doesn't know. `ArrayList`'s iterator notices on its next
step, and throws a `ConcurrentModificationException`. That's called **fail-fast**. Like the careful
guide, it stops, instead of skipping a song or playing one twice (the Gang of Four's warning: "you might
end up accessing an element twice or missing it completely"). But it's best effort: the `ArrayList`
docs say "the fail-fast behavior of iterators should be used only to detect bugs."

Remove the second-to-last song, and there's no exception at all. The loop simply ends, and the last
song is never checked.

```mermaid {alt="Sequence: the loop's iterator is at song two; the loop calls songs.remove on the list directly; the list changes; on the next step the iterator detects the change and throws ConcurrentModificationException. If the removed song was second to last, hasNext returns false instead and the last song is skipped." caption="The list changed behind the iterator's back."}
sequenceDiagram
  participant L as loop
  participant I as iterator
  participant A as ArrayList
  L->>I: next() returns a skipped song
  L->>A: remove(s)
  Note over A: the list changed
  L->>I: hasNext(), next()
  I-->>L: ConcurrentModificationException
  Note over L,I: second to last removed:<br/>hasNext() is false,<br/>the last song is never checked
```

The fix is to remove through the iterator. Its `remove` method deletes the song that `next` just
returned (it may be called once per call to `next`).

```java
Iterator<Song> it = songs.iterator();
while (it.hasNext()) {
    if (it.next().isSkipped()) it.remove();
}
```

Or let the list do the whole job, with `removeIf`:

```java
songs.removeIf(Song::isSkipped);
```

`remove` is an optional operation: the interface's default throws `UnsupportedOperationException`, so
an iterator over a read-only source simply doesn't support it.

## Your own iterator: a paged API

Writing your own iterator pays off when items come from somewhere awkward. Say an orders API returns
thirty orders a page. Callers want every order, and they don't care about pages. So a small iterator
does the paging for them. When its current page runs out, `hasNext` fetches the next one. It stops at
the first empty page.

```java
public class PagedIterator implements Iterator<Order> {
    private final OrderApi api;
    private List<Order> page = List.of();
    private int pos = 0;
    private int nextPage = 1;
    private boolean done = false;

    public PagedIterator(OrderApi api) { this.api = api; }

    public boolean hasNext() {
        if (pos == page.size() && !done) {
            page = api.fetch(nextPage++);   // one call per page
            pos = 0;
            done = page.isEmpty();
        }
        return pos < page.size();
    }

    public Order next() {
        if (!hasNext()) throw new NoSuchElementException();
        return page.get(pos++);
    }
}
```

Pages come in only when the loop gets there. A loop that stops early never fetches the rest. Wrap it in
an `Iterable`, and a lambda works here (`Iterable` has a single abstract method), and a plain for-each
loop walks every order.

```java
Iterable<Order> orders = () -> new PagedIterator(api);
for (Order o : orders) {
    ship(o);
}
```

```mermaid {alt="Sequence: the loop asks the PagedIterator hasNext; when the current page is used up, the iterator calls OrderApi.fetch for the next page; it returns orders from that page one by one; an empty page ends the walk." caption="The iterator hides the paging."}
sequenceDiagram
  participant L as for-each loop
  participant I as PagedIterator
  participant A as OrderApi
  L->>I: hasNext()
  I->>A: fetch(1)
  A-->>I: page 1 (30 orders)
  L->>I: next() … 30 times
  L->>I: hasNext()
  I->>A: fetch(2)
  A-->>I: page 2
  Note over I,A: an empty page<br/>sets done: the walk ends
```

## Internal iteration: forEach and streams

Everything so far was **external iteration**. Your loop asks for the next item, step by step. With
**internal iteration**, you hand over what to do, and the collection does the walking: `forEach` with a
lambda, or a stream.

```java
playlist.forEach(s -> play(s));

long longSongs = songs.stream()
        .filter(s -> s.seconds() > 300)
        .count();
```

The Java tutorial puts it this way: with internal iteration "your application determines what
collection it iterates, but the JDK determines how to iterate the collection." That also makes parallel
work easier. External iteration is more flexible. You can stop, or walk two collections side by side.
The Gang of Four note that comparing two collections is easy with an external iterator, and
"practically impossible" with an internal one.

It's the difference between a guided tour, where the guide walks and you listen, and your own audio
guide. And like an iterator, a stream is used only once: the stream docs say a new stream must be made
to revisit the same elements, and the source shouldn't be modified while a pipeline runs.

```mermaid {alt="Comparison: external iteration, where your loop calls hasNext and next and can stop early or walk two collections side by side; internal iteration, where you pass a lambda to forEach or a stream and the library decides how to walk, possibly in parallel." caption="External: you drive. Internal: you say what, the collection drives."}
flowchart LR
  subgraph EX["external"]
    direction TB
    E1["your loop calls<br/>hasNext(), next()"] --> E2["stop early,<br/>walk two side by side"]
  end
  subgraph IN["internal"]
    direction TB
    I1["you pass a lambda<br/>forEach, stream"] --> I2["the library decides how<br/>(even in parallel)"]
  end
  EX ~~~ IN
  class E1,E2 c4
  class I1,I2 c2
```

## When not to use it

- **You need a position** (the fifth song, a binary search): use a `List` and get by index.
- **Your class already wraps a standard list**: return an unmodifiable view, or a copy
  (`List.copyOf(songs)`). Don't write an iterator by hand.
- **You only transform or total the items**: a stream says it better.
- **A tiny private array that never leaves the class** can keep its plain loop.

Reach for an iterator when callers outside the class shouldn't know its shape, and that shape might
change.

```mermaid {alt="Decision: do callers outside the class walk its items? If not, a plain loop is fine. Do they need positions? Use a List and get. Is it already a standard collection? Return a view or a copy. Are you only transforming or totalling? Use a stream. Otherwise write an iterator." caption="Iterate when callers outside shouldn't know the shape."}
flowchart TD
  A{"callers outside walk the items?"} -->|no| N["plain loop"]
  A -->|yes| B{"need positions?"}
  B -->|yes| G["List and get(i)"]
  B -->|no| C{"already a standard collection?"}
  C -->|yes| V["return a view or a copy"]
  C -->|no| D{"only transform or total?"}
  D -->|yes| S["stream"]
  D -->|no| I["write an iterator"]
  class N,G,V muted
  class S c2
  class I good
```

## Recap

- Don't hand out the insides. Hand out an iterator, with `hasNext` and `next`, that keeps its own place.
- Implement `Iterable`, and for-each works. Change the storage, and the loops never notice.
- Remove through the iterator, or with `removeIf`; fail-fast exceptions are for finding bugs.
- An iterator can hide paging.
- `forEach` and streams are internal iteration.

```mermaid {alt="Recap chain: don't hand out the insides; hand out an iterator; implement Iterable so for-each works; the storage can change and the loops don't notice." caption="Walk it. Don't open it."}
flowchart LR
  A["don't hand out the insides"] --> B["hand out an iterator"] --> C["implement Iterable"] --> D["storage changes, loops don't"]
  class B c5
  class D good
```

Checklist:

- Does any getter hand out an internal array or a mutable list?
- Can callers walk the items with a for-each loop?
- Does anything remove from a collection inside a for-each loop?
- Would a stream say this loop more clearly?
- If the items come in pages or chunks, does an iterator hide that?

> **Walk it. Don't open it.**

Related lessons: [Factory Method](/patterns/factory-method-pattern/) (`iterator()` creates the
iterator), [Abstract Factory](/patterns/abstract-factory-pattern/),
[Encapsulation](/fundamentals/encapsulation/), [Polymorphism](/fundamentals/polymorphism/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Iterator.
- Java SE 21 API: [`Iterator`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Iterator.html),
  [`ArrayList`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/ArrayList.html) (fail-fast iterators),
  [`java.util.stream`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/stream/package-summary.html).
- The Java Language Specification, [§14.14.2 The enhanced for statement](https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.14.2).
- The Java Tutorials: [Aggregate Operations](https://docs.oracle.com/javase/tutorial/collections/streams/).
