Thursday, 17 August 2017

What is the advantage of iterating Collection using iterator?

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:

package javaRadarArrayList;

import java.util.ArrayList;
import java.util.Iterator;

public class UpdateList {

      public static void main(String[] args) {
            //create Array List
            ArrayList<String> javaRadarList = new ArrayList<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.

1 comment:

  1. Hi, I am David the creator of https://www.springmockexams.com and https://www.javamockexams.com.

    I really want to thank you for this post, I am going to share it on all my social media, if you do not mind!

    I am also really enthusiast to announce some very exciting news: to celebrate the imminent release of Spring 5 and Java 9 we launched our simulators SALE CAMPAIGN. We lowered the price of our simulators at www.springmockexams.com and www.javamockexams.com for limited time only.

    If the audience is interested in accessing OUR PRICE OFFER, they can take a look here http://www.cm.gy/sme and here http://www.clktr4ck.com/java

    Thanks and check your featuring on our social medias!

    David

    ReplyDelete

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.