Eksempelkode:

public class StringIterator implements Iterator<Character> {
    private String string;
    private int i = 0;
    
    public StringIterator(String string) {
        this.string = string;
    }
    @Override
    public boolean hasNext() {
        return i < string.length();
    }
    @Override
    public Character next() {
        char c = string.charAt(i);
        i = i + 1;
        return c;
    }
    @Override
    public void remove() {
        throw new UnsupportedOperationException("Støtter ikke remove");
    }
}

public class ListIterator implements Iterator<Character> {
    private List<Character> characters;
    private int i = 0;
    
    public ListIterator(List<Character> characters) {
        this.characters = characters;
    }
    @Override
    public boolean hasNext() {
        return i < characters.size();
    }
    @Override
    public Character next() {
        char c = characters.get(i);
        i = i + 1;
        return c;
    }
    @Override
    public void remove() {
        throw new UnsupportedOperationException("Støtter ikke remove");
    }
}

public class IterationExample {
    private String string;
    private List<Character> characters;
    
    public void init() {
        string = "Java er gøy";
        characters = Arrays.asList('J', 'a', 'v', 'a');
    }
    
    public void run() {
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            System.out.println(c);
        }
        Iterator<Character> stringIterator = new StringIterator(string);
        while (stringIterator.hasNext()) {
            char c = stringIterator.next();
            System.out.println(c);
        }
        for (int i = 0; i < characters.size(); i++) {
            char c = characters.get(i);
            System.out.println(c);
        }
        Iterator<Character> listIterator = characters.iterator();
        while (listIterator.hasNext()) {
            char c = listIterator.next();
            System.out.println(c);
        }
        for (char c : characters) {
            
        }
    }
    
    public static void main(String[] args) {
        IterationExample program = new IterationExample();
        program.init();
        program.run();
    }
}