Design Pattern

Iterator Pattern Design Patterns in Java

The iterator pattern comes under the behavioral patterns. The design uses iterator object, which stores the track of the current object in the list and the next object which is supposed to be iterated next. Iterator pattern takes the responsibility for the accessing and passing of the objects through the list and storing them in an iterator object.

Iterator Pattern

According to the Gang of Four:

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Iterator, in the sense of computer programming, is an object that allows the programmer to traverse a container, specifically lists. The interface of the container is the source for different types of iterators. Iterators are often tightly linked to the container to allow the operational semantics of the iterator.

To design, versatile and reusable object-oriented software, there are 23 well-known design patterns, the iterator pattern is one of them. The idea of Iterator pattern is to give a way to access the elements of the comprehensive object in a sequential manner without having the need to know about its hidden representation. For example, if a person writes a simple binary search algorithm in Java language. Due to the strong language used, the function signature is most likely to couple the algorithm to the particular collection types. To decouple the collection types from the algorithm, the iterator interface is required. This allows the algorithm to cover various types of data structures. This way, the user does not need to write separate algorithms for each data type and can make the algorithm functions for more than one data type, just by recycling it.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Patterns“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.

Benefits of using the Iterator pattern

There are following benefits of the Iterator pattern:

  • Easily access the items of the collection.
  • You can use multiple to access the item from the collection, because it support lot of variations in the traversal.
  • It provides a uniform interface for traversing different structures in a collection.

The iterator pattern is used in the object-oriented programming. It is the kind of design pattern where an iterator is used to traverse through a container and its elements, this helps in decoupling the algorithm and the elements of the container. Though, in some cases, it is not possible to decouple the algorithms because they are specified by the container (depends directly on it). The pattern prevents from the representation (data structures) of the container, to be exposed. The procedure can easily be performed with the representation, hidden. For each new data type, there will be no need for new algorithms to be defined. Defining and writing down new algorithms for each different data type can consume time and energy both. The iterator pattern helps save time and energy.

Characterizing entry and traversal operations in the comprehensive interface may be unbendable in order that it commits the collection to specific access and traversal operations. This makes it almost impossible to add new operations in future, not unless the collection interface has been changed in respective order.

The iterator pattern helps to define a separate object, iterator, that takes responsibility to access and traverse the collection object. This way, other objects do not get jumbled up. The clients that use an iterator, in order to access or traverse the container or elements of the container, will not know about its underlying data structure or representation. Various types of iterators can be used to access and traverse in different ways. By declaring new iterators, new traversal operations can be defined.

UML Class Structure

Let’s see the following UML diagram is showing the all components of Iterator design pattern:

Iterator
It is an interface or abstarct class for accessing and traversing items of the collections.
ConcreteIterator
It is implementation of the Iterator interface.
Aggregate
It is an interface to create an Iterator object
ConcreteAggregate
It is implementation of the Aggregate interface, it implements the Iterator creation interface to return an instance of the proper ConcreteIterator.

Example of Iterator Design Pattern

java.util.Iterator interface uses Iterator Design Pattern.

Step 1: Create interfaces.

Iterator.java

public interface Iterator {
   public boolean hasNext();
   public Object next();
}

Step 2: Container.java

public interface Container {
   public Iterator getIterator();
}

Step 3: Create concrete class implementing the Container interface.

This class has an inner class NameCollectionIterator implementing the Iterator interface.

NameCollection.java

public class NameRepository implements Container {
   public String names[] = {"Dinesh", "Anamika","Arnav", "Adesh", "Vinesh"};

   @Override
   public Iterator getIterator() {
      return new NameCollectionIterator();
   }

   private class NameCollectionIterator implements Iterator {

      int index;

      @Override
      public boolean hasNext() {
      
         if(index < names.length){
            return true;
         }
         return false;
      }

      @Override
      public Object next() {
      
         if(this.hasNext()){
            return names[index++];
         }
         return null;
      }		
   }
}

Step 4: Create a IteratorPatternDemo class.

IteratorPatternDemo.java

public class IteratorPatternDemo {
	
   public static void main(String[] args) {
      NameRepository namesRepository = new NameRepository();

      for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
         String name = (String)iter.next();
         System.out.println("Name : " + name);
      } 	
   }
}

Step 4: Let’s run this demo class and verify the output.

Name : Dinesh
Name : Anamika
Name : Arnav
Name : Adesh
Name : Vinesh
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago