Iterator Pattern In Java

Introduction

Iterator is a widely-used, simple, yet useful design pattern in both Java and .NET. In this article, I will focus on the Java version of the Iterator Pattern. Later, I will write another article for you about the .NET implementation of it.
 
Basically, the idea of the iterator pattern is to let the client code iterate over a collection. Usually, all the collections in Java have inbuilt support of iterator implementation. In Java, the iterator pattern implementation is straightforward. 
Iterator Pattern In Java


Basic iterator implementation


In Java, we have the Iterator interface (inside the java.util package). We can directly implement that interface into any collection where we need the iteration functionality.
 
In the Iterator, we have two abstract methods where we need to provide the implementation. 
  1. interface Iterator {  
  2.  boolean hasNext();  
  3.  Object next();  
  4. }  
Have a look at the following code.
  1. public class SampleRepository implements Iterator {  
  2.  private String[] elements = {  
  3.   "A",  
  4.   "B",  
  5.   "C",  
  6.   "D"  
  7.  };  
  8.  private int position = 0;  
  9.  @Override  
  10.  public boolean hasNext() {  
  11.   return position < elements.length;  
  12.  }  
  13.  @Override  
  14.  public Object next() {  
  15.   if (this.hasNext())  
  16.    return elements[position++];  
  17.   return null;  
  18.  }  
  19. }  
Here, the SampleRepository class directly implements the Iterator Interface and allows to iterate over the list of elements inside the class.
 
Let’s see how we can iterate the collection. 
  1. SampleRepository sampleRepository = new SampleRepository();  
  2. while (sampleRepository.hasNext()) {  
  3.  System.out.println(sampleRepository.next());  
  4. }  
Since this is a string list, we can iterate the collection and it will provide the following output.
 
Iterator Pattern In Java
 

What happens if the list is not a string list anymore?

Suppose we have our own type called ‘Employee’. 
  1. public class Employee {  
  2.  public int getId() {  
  3.   return id;  
  4.  }  
  5.  public void setId(int id) {  
  6.   this.id = id;  
  7.  }  
  8.  public String getName() {  
  9.   return name;  
  10.  }  
  11.  public void setName(String name) {  
  12.   this.name = name;  
  13.  }  
  14.  private int id;  
  15.  private String name;  
  16.  public Employee(int id, String name) {  
  17.   this.id = id;  
  18.   this.name = name;  
  19.  }  
  20. }  
  21. private Employee[] elements = {  
  22.  new Employee(1"A-Employee"),  
  23.  new Employee(2"B-Employee")  
  24. };  
Then, what will happen when we print the values? We will get a similar output of the following kind.
 
Iterator Pattern In Java
 
That is because once we print the collection, it prints the addresses of the employee references. Unless we do the casting, there’s no way to access the properties of the employee. So, we have to do the casting like this and print the names of the employees
  1. while (sampleRepository.hasNext()) {  
  2.  System.out.println(((Employee) sampleRepository.next()).getName());  
  3. }  

 

What is the solution?

 
Generic iterator implementation

What if we build an iterator that provides a generic way of iterating over a collection independent of its type?
  1. public class SampleRepositoryGeneric < T > implements Iterator {  
  2.  private Employee[] elements = {  
  3.   new Employee(1"A-Employee"),  
  4.   new Employee(2"B-Employee")  
  5.  };  
  6.  private int position = 0;  
  7.  @Override  
  8.  public boolean hasNext() {  
  9.   return position < elements.length;  
  10.  }  
  11.  @Override  
  12.  public T next() {  
  13.   if (this.hasNext())  
  14.    return (T) elements[position++];  
  15.   return null;  
  16.  }  
  17. }  
Here, we have made the sample repository to use <T>. And we have an easier and more efficient implementation once we call the collection for iteration. Actually, no casting!
  1. SampleRepositoryGeneric < Employee > sampleRepositoryGeneric = new SampleRepositoryGeneric < > ();  
  2. while (sampleRepositoryGeneric.hasNext()) {  
  3.  System.out.println(sampleRepositoryGeneric.next().getName());  
  4. }  
 
Further refactoring

There’s one more thing we could do to clean the code.
  1. public class SampleRepository < T > {  
  2.  private Employee[] elements = {  
  3.   new Employee(1"A-Employee-Refactored"),  
  4.   new Employee(2"B-Employee-Refactored")  
  5.  };private int position = 0;public Iterator < T > getIterator() {  
  6.   return new SampleRepositoryIterator();  
  7.  }  
  8.  private class SampleRepositoryIterator implements Iterator {  
  9.   @Override  
  10.   public boolean hasNext() {  
  11.    return position < elements.length;  
  12.   }  
  13.   @Override  
  14.   public T next() {  
  15.    if (this.hasNext())  
  16.     return (T) elements[position++];  
  17.    return null;  
  18.   }  
  19.  }  
  20. }  
Basically, what we have done is that we have made the iterator an internal class and exposed the iterator as a property to the outside users. So, we have encapsulated the iterator, and we can call the iterator like this.
  1. refactored.iterator.SampleRepository < Employee > sampleRepository1 = new refactored.iterator.SampleRepository < > ();  
  2. while (sampleRepository1.getIterator().hasNext()) {  
  3.  System.out.println(sampleRepository1.getIterator().next().getName());  
  4. }  
That's it for this article. Cheers!!