We can use for loop, advanced for loop or iterator for iterating over Collection.

But using iterator over other competitors gives some advantages like:

  • By using for loop you cannot update(add/remove) the Collection whereas with iterator we can easily update Collection.
Example for updating list by iterator:

packagejavaRadarArrayList;
importjava.util.ArrayList;
importjava.util.Iterator;
public class UpdateList {
      public static void main(String[] args) {
            //create Array List
            ArrayList<String> javaRadarList = newArrayList<String>();
            //Add elements to ArrayList
            javaRadarList.add(“Java”);
            javaRadarList.add(“Spring”);
            javaRadarList.add(“Hibernate”);
            javaRadarList.add(“EJB”);
            System.out.println(“Original list:” +javaRadarList);
           
            Iterator<String> itr = javaRadarList.iterator();
            while(itr.hasNext()){
                  String token = itr.next();
                  itr.remove();
                  System.out.println(“list afer modification:” +javaRadarList);
            }
                 
      }
}
OUTPUT:
Original list:[Java, Spring, Hibernate, EJB]
list afer modification:[Spring, Hibernate, EJB]
list afer modification:[Hibernate, EJB]
list afer modification:[EJB]
list afer modification:[]
NOTE: Try to remove object from Collection using for loop and see if you can or not.

  • In situations where there is no idea of what type of Collection will be used we can use iterator to traverse over the collection as all Collection implements iterator interface.
You may also like to read:

  • ArrayList vs LinkedList
  • ArrayList vs Vector
  • Collection vs Collections
  • ArrayList vs HashSet
  • Iterator vs Enumeration
  • interface vs abstract class

Source link

What is the advantage of iterating Collection using iterator?

Leave a Reply

Your email address will not be published. Required fields are marked *