AlgoViz

Iterator pattern

medium 45 min

The Iterator pattern gives access to the elements of a collection one after the other without showing how they are stored.

Watch lesson4:34

Where it shows up

The same pattern appears across everyday software.

  • Java collections

    ArrayList, LinkedList, TreeSet and HashSet implement Iterable. The iterator of ArrayList is documented as fail-fast: after a structural change that did not go through the iterator, it throws ConcurrentModificationException.

  • java.util.concurrent

    Iterators of most concurrent collections are weakly consistent: they may run together with other operations and never throw that exception. CopyOnWriteArrayList offers a snapshot instead.

  • JDBC ResultSet

    A cursor over the rows of a query. It starts before the first row. next moves it and returns false when there are no more rows, so it drives a while loop.

  • Python itertools

    Iterator building blocks such as chain, islice, tee and groupby. They take walks and return walks, without collecting anything.

  • Directory walks

    Python's os.scandir and os.walk, and Files.list and File.listFiles in Java. The first and the third produce entries step by step, os.walk one folder after the other, and listFiles returns a whole array. Compare them on a folder with a million files.

  • MongoDB cursors

    find returns a cursor to the documents that match, not the documents themselves. Drivers fetch batches behind it.

  • AWS SDK paginators

    boto3 paginators are an abstraction over iterating an entire result set of a truncated API operation. The caller loops and the marker is handled inside.

  • JavaScript iteration protocols

    Any object can become iterable by following two protocols. An iterator may offer return, which is called when a for of loop stops early, so that it can clean up.

  • Rust Iterator

    One required method, next. Dozens of others such as map and filter are built on it, and they are lazy.

  • C# iterators

    yield return inside a method makes the compiler write the iterator. foreach consumes it through IEnumerable.