FastFoodCoding

Login


Connect with one of the following accounts





Login

Please wait while we redirect...

Views: 316   



Iterator is helpful to iterate through items especially when you are reading data from a database/ external source where the data is huge and you don't want to waste the memory by loading all the items at once. There are two ways of using Iterator one is with while loop and another one is with for loop

1. Using while loop

Following code snippet shows how to loop on iterator using while loop

while(iterator.hasNext()){
    String value = iterator.next();
    System.out.println("value:" + value);  
}

2. Using for loop

Following code snippet shows how to loop on iterator using for loop

for(;iterator.hasNext();){
    String value = iterator.next();
    System.out.println("value:" + value);  
 }

Complete Program

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

public class IteratorLoop {
    public static void main(String[] args) {

        List<String> colors = new ArrayList<>();
        colors.add("white");
        colors.add("blue");
        colors.add("red");

        Iterator<String> iterator = null;

        // 1. Using while loop
         iterator = colors.iterator();

        while(iterator.hasNext()){
            String value = iterator.next();
            System.out.println("value:" + value); 
        }

        // 2. Using for loop
         iterator = colors.iterator();

         for(;iterator.hasNext();){
             String value = iterator.next();
             System.out.println("value:" + value);  
         }

    }

}



On By


Top Tutorials

Top Questions

Top Articles

Top Blogs

Top News