Iterators

  • An iterator is an Object that enables to cycle through a collection , obtain or remove elements.
  • Before you can access a collection through an iterator , you must obtain one.
  • Each of the collection classes provides an iterator() method that returns an iterator to the start of the collection.
  • By using this iterator object ,  we can acccess each elements in the collection , one element at a time.
  • The iterator class provides the following methods-
  • hasNext() – Returns true if there is atleast one or more element ;Otherwise it return false.
  • next() – Return the next object & advance the iterator.
  • remove() – Removes the last object that was returned by the next form the collection.
  • Iterator class must be imported from java.util package.
Example-
import java.util.Iterator;
import java.util.LinkedList;
public class Myclass{
     public static void main(String args[]){
       LinkedList<String> animals = new LinkedList<String>();
       animals.add("fox");
       animals.add("cat");
       animals.add("dog");
       animals.add("rat");
       Iterator<String> it = animals.iterator();
       String value = it.next();
       System.out.println(value);
   }
}
output-
fox
  • it.next() returns the first element in the list and then moves the iterator on to the next element.
  • Each time you call it.next() , the iterator moves to the next element of the list
  • Typically , iterator are used in loops. At each iteration of the loop , you can access the corresponding list element.
  • Example-
    import java.util.Iterator;
    import java.util.LinkedList;
    public class Myclass{
         public static void main(String args[]){ 
                LinkedList<String> animals = new LinkedList<String>(); 
                animals.add("fox"); 
                animals.add("cat"); 
                animals.add("dog"); 
                animals.add("rat"); 
                Iterator<String> it = animals.iterator(); 
                while(it.hasNext()){
                      String value = it.next();
                      System.out.println(value);
             }
    }
    Output-
    fox
    cat
    dog
    rat