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.

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.
- interface Iterator {
- boolean hasNext();
- Object next();
- }
Have a look at the following code.
- public class SampleRepository implements Iterator {
- private String[] elements = {
- "A",
- "B",
- "C",
- "D"
- };
- private int position = 0;
- @Override
- public boolean hasNext() {
- return position < elements.length;
- }
- @Override
- public Object next() {
- if (this.hasNext())
- return elements[position++];
- return null;
- }
- }
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.
- SampleRepository sampleRepository = new SampleRepository();
- while (sampleRepository.hasNext()) {
- System.out.println(sampleRepository.next());
- }
Since this is a string list, we can iterate the collection and it will provide the following output.

What happens if the list is not a string list anymore?
Suppose we have our own type called ‘Employee’.
- public class Employee {
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- private int id;
- private String name;
- public Employee(int id, String name) {
- this.id = id;
- this.name = name;
- }
- }
- private Employee[] elements = {
- new Employee(1, "A-Employee"),
- new Employee(2, "B-Employee")
- };


Mahesh ChandPosted May 24, 2019, 2:13 PM
Thank you, Eranda.