Sunday, 28 May 2017

Traverse Arraylist using ListIterator

Note: List iterator has the capability to traverse the given list in both forward direction as well as backward direction.

For forward direction traversal it has got two method hasNext() & next()
For backward direction travrsal it has got two method hasPrevious() & previous()

Look at their usage in below code snippet.


package javaRadarArrayList;

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

public class ListItrTraversal {

      public static void main(String[] args) {
            //create Array List
            ArrayList<String> javaRadarList = new ArrayList<String>();
            //Add elements to ArrayList
            javaRadarList.add("Java");
            javaRadarList.add("Jquery");
            javaRadarList.add("Spring");
            javaRadarList.add("Hibernate");
            javaRadarList.add("EJB");

            //creating list iterator to traverse over javaRadarList
            ListIterator<String> listIterator = javaRadarList.listIterator();

            System.out.println("Traversal in forward direction");
            while(listIterator.hasNext()){
                  System.out.println(listIterator.next());
            }
           
            System.out.println("Traversal in backward direction");
            while(listIterator.hasPrevious()){
                  System.out.println(listIterator.previous());
            }
      }

}


OUTPUT:

Traversal in forward direction
Java
Jquery
Spring
Hibernate
EJB
Traversal in backward direction
EJB
Hibernate
Spring
Jquery
Java 

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.