Search⌘ K
AI Features

Iterator Pattern

Explore the Iterator design pattern to understand how to traverse different types of collections sequentially without revealing their internal structure. Learn to implement external iterators in Java, simplifying client access to diverse collections while maintaining separation of concerns.

What is it ?

Iterate literally means to perform repeatedly. A for loop iterates over an array i.e. it accesses the array repeatedly. If you are familiar with Java then you would already have come across this pattern while working with Java Collections. A brief demonstration is below.

        ArrayList<String> companiesIWantToInterviewFor = new ArrayList<>();
        companiesIWantToInterviewFor.add("SnapChat");
        companiesIWantToInterviewFor.add("Twitter");
        companiesIWantToInterviewFor.add("Tesla");

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

The iterator allows a consumer to go over the elements of a collection without knowing how the collection is implemented. A collection can be a list, array, arraylist, hashmap or any other fancy datastructure. A collection signifies a bunch of objects. It doesn't specify any ordering or properties about the objects it holds. An iterator is formally defined as a pattern that allows traversing the elements of an aggregate or a collection sequentially without exposing the underlying implementation.

The iterator pattern extracts out the responsibility of traversing over an aggregate out of the aggregate's interface and encapsulates it in the iterator class, thereby simplifying the aggregate's interface.

Class Diagram

The class diagram consists of the following entities

  • Iterator
  • Concrete Iterator
  • Aggregate
  • Concrete Aggregate
widget
...