Iterator Pattern
This lesson discusses how the underlying elements that make up an aggregate object can be looped through without exposing implementation details to clients.
We'll cover the following
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.
Get hands-on with 1400+ tech skills courses.