Iterator Pattern

We’re going to create a Iterator interface which narrates navigation method and aContainer interface which retruns the iterator . Concrete classes implementing theContainer interface will be responsible to implement Iterator interface and use it

IteratorPatternDemo, our demo class will use NamesRepository, a concrete class implementation to print a Names stored as a collection in NamesRepository.

Iterator Pattern UML Diagram

Step 1

Create interfaces.

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

public interface Container {
   public Iterator getIterator();

Step 2

Create concrete class implementing the Container interface. This class has inner classNameIterator implementing the Iterator interface.

public class NameRepository implements Container {
   public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};

   public Iterator getIterator() {
      return new NameIterator();

   private class NameIterator implements Iterator {

      int index;

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

      public Object next() {
            return names[index++];
         return null;

Step 3

Use the NameRepository to get iterator and print names.

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

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

Step 4

Verify the output.

Name : Robert
Name : John
Name : Julie
Name : Lora