DEV Community

eidher
eidher

Posted on • Updated on

Iterator Pattern

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

Top comments (1)

Collapse
 
eidher profile image
eidher • 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.