Iterate through an ArrayList using a ListIterator in Java

Java 8Object Oriented ProgrammingProgramming

A ListIterator can be used to traverse the elements in the forward direction as well as the reverse direction in an ArrayList.

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

The method hasPrevious( ) in ListIterator returns true if there are more elements in the ArrayList while traversing in the reverse direction and false otherwise. The method previous( ) returns the previous element in the ArrayList and reduces the cursor position backward.

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("Apple");
      aList.add("Mango");
      aList.add("Guava");
      aList.add("Orange");
      aList.add("Peach");
      ListIterator i = aList.listIterator();
      System.out.println("The ArrayList elements in the forward direction are: ");
      while (i.hasNext()) {
         System.out.println(i.next());
      }
      System.out.println("\nThe ArrayList elements in the reverse direction are: ");
      while (i.hasPrevious()) {
         System.out.println(i.previous());
      }
   }
}

Output

The output of the above program is as follows

The ArrayList elements in the forward direction are

Apple
Mango
Guava
Orange
Peach
The ArrayList elements in the reverse direction are:
Peach
Orange
Guava
Mango
Apple
raja
Published on 18-Jan-2019 05:43:17
Advertisements