Iterator interface example in java

The List and Set collections provide Iterators, which are objects that allow going over all the elements of a collection in sequence. The java.util.Iterator interface provides for one-way traversal, The Iterator is a replacement for the older Enumeration class which was used before collections were added to Java.

Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.

Create an Iterator

You can create the Iterator by calling the method of iterator() of that collections like List, Set or other data collection with Iterator.

Methods in Iterator

Boolean hasNext()

This method returns true if the iteration has more elements.

Object next()

This method returns the next element in the iteration.

void remove()

This method removes from the underlying collection the last element returned by the iterator (optional operation).

Example of Iterator

This example iterates the list which has the type of string objects.

package com.java.connect.collection;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ArrayListExample {
    public static void main(String[] args) {
        List<string> list = new ArrayList<string>();
        list.add("test1");
        list.add("test2");
        list.add("test3");
        list.add("test4");
        list.add("test5");
        // Print all the objects in list
        System.out.println(list);
        // Iterate all the objects from the list using Iterate
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            String string = (String) iterator.next();
            System.out.println(string);
        }
    }
}

The output of the above code will be:

[test1, test2, test3, test4, test5]
The value of object is : test1
The value of object is : test2
The value of object is : test3
The value of object is : test4
The value of object is : test5