Iterator Interface Example Java Program


Definition

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.

Syntax

ListIterator<variable-type> variable-name= list-name.listIterator();

Iterator Interface Example Program

import java.util.*;

public class IteratorExample {

    public static void main(String[] args) {
        List<String> locationsList = new ArrayList<String>();

        locationsList.add("Chennai");
        locationsList.add("Mumbai");
        locationsList.add("Hyderabad");
        locationsList.add("Lucknow");
        locationsList.add("Bangaluru");

        System.out.println("List is : " + locationsList);

        System.out.println("Printing list items using Iterator");

        ListIterator<String> locationsIterator = locationsList.listIterator();

        while (locationsIterator.hasNext()) {
            System.out.println(locationsIterator.next());
        }
    }
}

Sample Output

List is : [Chennai, Mumbai, Hyderabad, Lucknow, Bangaluru]
Printing list items using Iterator
Chennai
Mumbai
Hyderabad
Lucknow
Bangaluru