Use ListIterator to traverse an ArrayList in the forward direction in Java


A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in the List Collection. So the ListIterator is only valid for classes such as LinkedList, ArrayList etc.

The method hasNext( ) in ListIterator returns true if there are more elements in the List and false otherwise. The method next( ) returns the next element in the List and advances the cursor position.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> aList = new ArrayList<String>();
      aList.add("Amanda");
      aList.add("Peter");
      aList.add("Julie");
      aList.add("James");
      aList.add("Emma");
      ListIterator li = aList.listIterator();
      System.out.println("The ArrayList elements in the forward direction are: ");
      while (li.hasNext()) {
         System.out.println(li.next());
      }
   }
}

Output

The ArrayList elements in the forward direction are:
Amanda
Peter
Julie
James
Emma

Now let us understand the above program.

The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. Then the ArrayList elements are displayed in the forward direction using an iterator which makes use of the ListIterator interface. A code snippet which demonstrates this is as follows −

ArrayList<String> aList = new ArrayList<String>();
aList.add("Amanda");
aList.add("Peter");
aList.add("Julie");
aList.add("James");
aList.add("Emma");
ListIterator li = aList.listIterator();
System.out.println("The ArrayList elements are: ");
while (li.hasNext()) {
   System.out.println(li.next());
}

Updated on: 30-Jul-2019

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements