Tuesday 25 March 2014

iterator : Traverse the list

Iterator<E> iterator()
    Returns an iterator over the elements in this list in proper sequence.

import java.util.*;
class ListIterator{
 public static void main(String args[]){
  List<Long> myList = new ArrayList<> ();
  
  /* Add Elements to the list */
  myList.add(10L);
  myList.add(-856L);
  myList.add(-345L);
  myList.add(1234L);
  myList.add(-190L);
  
  Iterator<Long> iter = myList.iterator();
  
  System.out.println("Elements in the list are");
  /*Iterate over the elements in the List */
  while(iter.hasNext())
   System.out.println(iter.next());
 }
}

Output
Elements in the list are
10
-856
-345
1234
-190

Iterators support to remove elements while traversing. See the below Example.

import java.util.*;
class ListIterator{
 public static void main(String args[]){
  List<Long> myList = new ArrayList<> ();
  
  /* Add Elements to the list */
  myList.add(10L);
  myList.add(-856L);
  myList.add(-345L);
  myList.add(1234L);
  myList.add(-190L);
  
  Iterator<Long> iter = myList.iterator();
  
  System.out.println("Elements in the list are");
  /*Iterate over the elements in the List */
  while(iter.hasNext()){
   System.out.println(iter.next());
   iter.remove();
  }
  System.out.println("Elements in the myList after calling remove on iterator " + myList);
 }
 
}

Output
Elements in the list are
10
-856
-345
1234
-190
Elements in the myList after calling remove on iterator []

remove() of Iterator removes from the underlying collection the last element returned.

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment