How to use Iterator to read all items
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);
}
}
}