Skip to main content

What is the difference between an external and an internal iterator?

External and internal iterators differ in who controls the traversal of the collection, the client or the collection itself.


1. External Iterator

The Essence

The client controls the iteration itself - manually requesting elements from the iterator. This is the most common variant (for example, Iterator in Java, for...of in Python).

Example (Java)

java
Iterator<String> it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); }

The client decides when to move to the next element, when to stop, and what to do between steps.

Advantages

  • Full control over the traversal process.
  • Can be interrupted, elements can be skipped, several iterations can be combined.
  • Easy to implement nested traversals or filtering in the code.

Disadvantages

  • The client has to write the loop itself and track the iterator's state.
  • Errors are possible (for example, calling next() without checking hasNext()).

2. Internal Iterator

The Essence

The collection controls the traversal itself, the client simply passes an action (a function, a lambda) to be executed for each element.

Example (Java)

java
list.forEach(item -> System.out.println(item));

Here the collection iterates over all the elements itself and calls the passed function.

Advantages

  • Cleaner code, no manual loops.
  • Safer: the client cannot break the traversal sequence.
  • Fits parallel and stream-based APIs (for example, stream().forEach() in Java).

Disadvantages

  • Less control: you cannot interrupt the traversal or mix several iterations.
  • You cannot nest one internal iterator inside another without extra workarounds.

Comparison

CharacteristicExternal IteratorInternal Iterator
Who controls the iterationThe clientThe collection
FlexibilityHighLow
Ease of useLowerHigher
Ability to interruptYesLimited
Example in JavaIterator, while (it.hasNext())forEach, Stream.forEach()

Conclusion

  • External iterator, the choice when control and flexibility are needed (for example, conditional processing, stopping).
  • Internal iterator, when simplicity and safety matter (for example, processing all elements in sequence).

Summary:

An external iterator "hands out elements on the client's demand", while an internal one "controls the traversal itself and merely calls client code".

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.