Use ListIterator to traverse an ArrayList in the reverse direction 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 the List Collection. So the ListIterator is only valid for classes such as LinkedList, ArrayList etc.

The method hasPrevious( ) in ListIterator returns true if there are more elements in the List while traversing in the reverse direction and false otherwise. The method previous( ) returns the previous element in the List 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("Amanda");
      aList.add("Peter");
      aList.add("Julie");
      aList.add("James");
      aList.add("Emma");
      ListIterator<String> li = aList.listIterator();
      while (li.hasNext()) {
         li.next();
      }
      System.out.println("The ArrayList elements in the reverse direction are: ");
      while (li.hasPrevious()) {
         System.out.println(li.previous());
      }
   }
}

Output

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

Now let us understand the above program.

The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. 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");

Then the ListIterator interface is used to display the ArrayList elements in the reverse direction. A code snippet which demonstrates this is as follows −

ListIterator<String> li = aList.listIterator();
while (li.hasNext()) {
   li.next();
}
System.out.println("The ArrayList elements in the reverse direction are: ");
while (li.hasPrevious()) {
   System.out.println(li.previous());
}
raja
Published on 30-Jan-2019 07:12:13
Advertisements