Java program to iterate through a list using ListIterator

Iterate through a list using Listiterator in Java :

We can iterate through all elements of a list using ‘Listiterator’ in Java. Main advantage of Listiterator is that you can iterate in both direction. i.e. access one by one element from first to last or from last to first.
Create one list and create one iterator from this by using ‘.listIterator()’ method. To check if the iterator is pointing to any element, ‘hasNext()’ or ‘hasPrevious()’ methods are used. To get the current element iterator is pointing on, we can use ‘next()’ or ‘previous()’ methods. Below example will clarify your doubts :

import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;

public class Main {

    public static void main(String[] args) {
        ArrayList myList = new ArrayList();
        myList.addAll(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

        ListIterator iterator = myList.listIterator();

        System.out.println("Iterating in forward direction : ");
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }

        System.out.println();

        System.out.println("Iterating in backward direction : ");
        while (iterator.hasPrevious()) {
            System.out.print(iterator.previous() + " ");
        }
    }

}

It will print the elements one by one from first to last with the first print and from last to first with the second print statement. Output :

Iterating in forward direction :
1 2 3 4 5 6 7 8 9 10
Iterating in backward direction :
10 9 8 7 6 5 4 3 2 1

Leave a Reply