Friday 4 April 2014

Iterate the List

ListIterator<E> listIterator()
    List Provides way to iterate the List both forward and backward way.

import java.util.*;

class listIteratorEx{
 public static void main(String args[]){
  List<Integer> myList = new LinkedList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
  myList.add(50);
  
  /* traverse the list in Forward */
  ListIterator<Integer> iter = myList.listIterator();
  System.out.println("Forward Traversal Of the List is");
  while(iter.hasNext()){
   System.out.print(iter.next() + " ");
  }
  System.out.println();
  
  /* traverse the list in Backward */
  System.out.println("Backward Traversal Of the List is");
  while(iter.hasPrevious()){
   System.out.print(iter.previous() + " ");
  }
  System.out.println();
  
 }
}

Output

Forward Traversal Of the List is
10 20 30 40 50
Backward Traversal Of the List is
50 40 30 20 10

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment