Java Behavioral Design Patterns – Iterator Design Pattern

Iterator Design Pattern is one of the Behavioural design patterns in Java. It is used for traversing through the collection of data in a particular class.

This pattern hides the actual implementation of traversal through the collection. The application programs just use iterator methods for different purposes. Iterator pattern allows accessing the elements of a collection object in a sequential manner without knowledge of its structure. Key points to remember about this interface are:

  • This pattern is used when you foresee a collection is traversed with different types of criteria.
  • The collection object should be accessed and traversed without exposing its data structure.
  • New traversal operations should be defined for collection object without changing its interface.

<Here are ALL other Java Design Patterns, explained in detail with examples>

Iterator Design Pattern by Example

To understand we will consider a simple example of BookService. We will also implement a custom iterator which will traverse based on the publisher of the book.

First things first, let us define our iterator interface.

Our custom iterator interface has 2 methods. One will determine if there are any more elements to traverse. The other method next() will give us actual element.

As we are iterating over books, we will define simple POJO as:

Our base classes are ready, let’s define BookService and its custom iterator:

Please note that this custom iterator is specific to this type of collection. Hence we have added that as a private class to our main class.

The custom iterator accepts publisher name to check and iterate over only books of that publisher.

Running the example

During our test run, we have prepared a list of few books and trying to iterate over them. The output:

Advantages:

  • Iterator design pattern hides the actual implementation of traversal through the collection and client programs just use iterator methods.
  • The iterator pattern can be implemented in a customized way in Java according to need.
  • We can use several iterators on the same collection.

Conclusion

So it was fairly simple to understand Iterator Design Pattern. Please feel free to ask a question or comment.

You can download the code from our GitHub repository:

Download from Git

 

<Here are ALL other Java Design Patterns, explained in detail with examples>

Add a Comment

Your email address will not be published. Required fields are marked *