Iterator Design Pattern in Java

Iterator pattern falls under behavioral design pattern. Iterator pattern is very commonly used design pattern in Java. This pattern is used to iterate through a collection of objects without exposing its underlying representation. It is used to access the elements of an aggregate object sequentially.

For example, Java’s collections like ArrayList and HashMap have implemented the iterator pattern.

Class Diagram

Iterator Pattern in Java

Implementation
We can write our own iterator.
Create an interface with below operations

package com.roytuts.designpattern.iterator;
public interface MyIterator {
  boolean hasNext();
  Object next();
}

Create another interface to get the above iterator

package com.roytuts.designpattern.iterator;
public interface MyContainer {
  MyIterator getMyIterator();
}

Now we create a class which holds some designations through which we will be iterating and check whether the array element has next element from its current position.

package com.roytuts.designpattern.iterator;
public class Designations implements MyContainer {
  private String[] designations = { "Analyst", "Associate", "Sr. Associate", "Manager", "Sr. Manager", "Associate Director", "Director",
      "Associate VP", "VP" };
  @Override
  public MyIterator getMyIterator() {
    return new DesignationIterator();
  }
  private class DesignationIterator implements MyIterator {
    private int index;
    @Override
    public boolean hasNext() {
      if (index < designations.length) {
        return true;
      }
      return false;
    }
    @Override
    public Object next() {
      if (this.hasNext()) {
        return designations[index++];
      }
      return null;
    }
  }
}

We create a test class which will iterate through the collection of objects and display

package com.roytuts.designpattern.iterator;
public class IteratorPatternTest {
  /**
   * @param args
   */
  public static void main(String[] args) {
    Designations designations = new Designations();
    for (MyIterator myIterator = designations.getMyIterator(); myIterator.hasNext();) {
      String designation = (String) myIterator.next();
      System.out.println("Designation : " + designation);
    }
  }
}

OutputĀ 

Designation : Analyst
Designation : Associate
Designation : Sr. Associate
Designation : Manager
Designation : Sr. Manager
Designation : Associate Director
Designation : Director
Designation : Associate VP
Designation : VP

That’s all. Thanks for your reading.

Leave a Reply

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