Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

Iterator

The Iterator is an interface available in the java.util package. We use a java.util.Iterator type object to traverse a collection in forward order.

java.util.Iterator:

publicinterface java.util.Iterator{
public abstract booleanhasNext();
public abstract Object next();
public void remove();
public void forEachRemaining(java.util.function.Consumer);
}

In different collections, there is a dedicated method to obtain an Iterator type object, such as the public java.util.Iterator<E> iterator() method in the java.util.ArrayList class.

Important point of Iterator:

With an Iterator, we can iterate through a collection in forward order only.
Using the same Iterator type object, we can't iterate through a collection more than once.

            
importjava.util.ArrayList;
importjava.util.Iterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListlist = newArrayList();
      list.add(101);
      list.add(202);
      list.add(303);
      list.add(404);
      list.add(505);
      Iteratoriterator = list.iterator();
      while (iterator.hasNext()) {
         System.out.println(iterator.next());
      }
      System.out.println("--------");
      while (iterator.hasNext()) {
         System.out.println(iterator.next());
      }
   }
}
    101
    202
    303
    404
    505
    --------
            

In this example, we create a java.util.Iterator type object using the iterator() method of the java.util.ArrayList class. By using the hasNext() and next() methods, we iterate through the ArrayList in the forward direction. However, it is important to note that attempting to iterate through the ArrayList using the same Iterator object does not produce any output.

While iterating through a collection, adding or removing elements using the add() and remove() methods of java.util.ArrayList with the collection leads to a java.util.ConcurrentModificationException.

            
importjava.util.ArrayList;
importjava.util.Iterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListlist = newArrayList();
      list.add(101);
      list.add(202);
      list.add(303);
      list.add(404);
      list.add(505);
      System.out.println("list :- " + list);
      System.out.println("-------------------------");
      Iteratoriterator = list.iterator();
      while (iterator.hasNext()) {
         System.out.println(iterator.next());
         // list.remove(new Integer(303)); :- java.util.ConcurrentModificationException
         // list.add(new Integer(303)); :- java.util.ConcurrentModificationException
      }
      System.out.println("-------------------------");
      System.out.println("list :- " + list);
   }
}
    list :- [101, 202, 303, 404, 505]
    -------------------------
    101
    202
    303
    404
    505
    -------------------------
    list :- [101, 202, 303, 404, 505]
            

Important Method of java.util.Iterator Interface:

1. public abstract booleanhasNext(): It is an abstract method of the java.util.Iterator interface. We use the hasNext() method to check whether the current working collection has more elements to iterate. If yes, then it returns true; otherwise, it returns false.

2. public abstract Object next() : When we create a new iterator, the cursor initially points just before the first element. When we invoke the next() method, it returns the next element of the current working collection (on the first invocation, it returns the first element of the collection and moves the cursor to the first position itself). If the iteration has no more elements, it throws a NoSuchElementException.

3. public void remove() : It removes the next element of the iterator. It throws UnsupportedOperationException if the current iterator does not support the remove operation and throws IllegalStateException when we call the remove() method without previously calling the next() method, or if we have called the remove() method more than once after the calling of next() method.

            
importjava.util.ArrayList;
importjava.util.Collection;
importjava.util.Collections;
importjava.util.Iterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      ArrayListlist = newArrayList();
      list.add(101);
      list.add(202);
      list.add(303);
      list.add(404);
      list.add(505);
      System.out.println("Before Iteration list :- " + list);
      Iteratoriterator = list.iterator();
      while (iterator.hasNext()) {
         // iterator.remove(); --->java.lang.IllegalStateException
         System.out.println(iterator.next());
         iterator.remove();
         // iterator.remove(); --->java.lang.IllegalStateException
      }
      System.out.println("After Iteration list :- " + list);
   }
}
    Before Iteration list :- [101, 202, 303, 404, 505]
    101
    202
    303
    404
    505
    After Iteration list :- []
            

In this example, we create an object of java.util.Iterator type by invoking the iterator() method of the java.util.ArrayList class. We then remove elements using the remove() method of the java.util.Iterator interface.