Iterator Design Pattern

Overview

Syntax

Iterator iterator = c.iterator();

Methods of Iterator Interface in java

Example 1

public class I1Intro {
    public static void main(String ...args) {
        List<Integer> numbers =  List.of(1,2,3,4,5,6);//Arrays.asList()
        Integer sum = 0;//Integer.MIN_VALUE;

        //Declarative Style === what to do, delegate how to do to Java
        int sumTotal = numbers.stream().parallel()
                .mapToInt(number -> number)
                .sum();
        System.out.println(sumTotal);
    }
}

Example 2

Implementation Example 3

Creating an interface Iterator.java, Container.java

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

Creating concrete class implementing the container interface.

public class Namerepository implements Container{
public String names[] = {"Deepthi", "Nitin", "Keerthi"};
@Override
public Iterator getIterator(){
return new NameIterator();
}
private class NameIterator implements Iterator{
int index = 0;
@Override
public boolean hasNext(){
if(index < names.length){
return true;
}
return false;
}

@Override
public Object next(){
if(this.hasNext()){
return names[index++];
}
return null;
}
}

Using the NameRepository to get iterator and print names IteratorPatternDemo.java

public class IteratorPtterndemo{
public ststic void main(String[] args){
NameRepository namesRepository = new NameRepository();
for(Iterator iterator = namesRepository.getIterator();
iterator.hasNext();
)
{
String name = (String)iter.next();
System.out.println("Name:"+name);
}
}
}

Advantages of iterator Design pattern