Data Structures

Iterators


In Java, Iterator is an interface within the java.util package used to traverse the elements of a collection sequentially. It allows you to access and potentially remove elements from a collection without needing to know the collection’s underlying implementation details.

Key methods of the Iterator interface:

Iterator and the enhanced for-each loop:

The enhanced for-each loop (introduced in Java 5), which can be used for simple iteration without element removal, uses an Iterator internally. For example:

        List<String> names = new ArrayList<>();
        // Populate list
        for (String name : names)
        {
            System.out.println(name);
        }

How to use an Iterator explicitly:

        Iterator<String> it = names.iterator();
        while (it.hasNext())
        {
            String name = it.next();
            System.out.println(name);
        }
        while (it.hasNext())
        {
            String name = it.next();
            if (name.equals("John"))
            {
                it.remove(); // Removes "John" from the 'names' list
            }
        }

Exceptions:

There are several exceptions that can be thrown by the remove method or other code when an Iterator is active.

Additional Functionality: