DEV Community

loading...

Iterator Pattern

eidher
Java Developer
・1 min read

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

Alt Text

Participants

  • Iterator: defines an interface for accessing and traversing elements.
  • ConcreteIterator: implements the Iterator interface. Keeps track of the current position in the traversal of the aggregate.
  • Aggregate: defines an interface for creating an Iterator object
  • ConcreteAggregate: implements the Iterator creation interface to return an instance of the proper ConcreteIterator

Code

public class Main {

    public static void main(String[] args) {
        String items[] = { "Item A", "Item B", "Item C", "Item D" };
        Aggregate aggregate = new ConcreteAggregate(items);
        for (Iterator iter = aggregate.getIterator(); iter.hasNext();) {
            String item = (String) iter.next();
            System.out.println(item);
        }
    }
}

public interface Aggregate {
     Iterator getIterator();
}

public class ConcreteAggregate implements Aggregate {
    private String items[];

    public ConcreteAggregate(String[] items) {
        this.items = items;
    }

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

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

public class ConcreteIterator implements Iterator {

    private String items[];
    private int index;

    public ConcreteIterator(String[] items) {
        this.items = items;
    }

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

    @Override
    public Object next() {
        if (this.hasNext()) {
            return items[index++];
        }
        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Item A
Item B
Item C
Item D
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
pjotre86 profile image
pjotre86 • Edited

Thanks!
Would you please help me to understand when this level of abstraction is actually useful?
I'm asking because in this example 99% of all java developers would probably just do a

items.forEach(System.out::println);
Collapse
eidher profile image
eidher Author • Edited

forEach is a defult method of the Iterable interface which uses the java.util.Iterator interface. So, at the end of the day, implicitly is the same. Of course, we do not need to reinvent the wheel. I would use your code.