Java Iterator iterate List

Introduction

To iterate List with Iterator in Java

//get Iterator from list
Iterator<String> itr = al.iterator(); 

//use loop to iterate one by one
while(itr.hasNext()) { 
      String element = itr.next(); 
      System.out.print(element + " "); 
} 
    

Full source


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; 
 
public class Main { 
  public static void main(String args[]) { 
    // Create an array list. 
    List<String> al = new ArrayList<String>(); 
     /*from   w w  w  .jav a2 s.c  o m*/
    // Add elements to the array list. 
    al.add("SQL"); 
    al.add("Java"); 
    al.add("Javascript"); 
    al.add("CSS"); 
    al.add("HTML"); 
    al.add("Demo2s.com"); 
    al.add(1, "Hi"); 
 
    System.out.println(al);
    
    // Use iterator to display contents of al. 
    System.out.print("Original contents of al: "); 
    Iterator<String> itr = al.iterator(); 
    while(itr.hasNext()) { 
      String element = itr.next(); 
      System.out.print(element + " "); 
    } 
    
  } 
}



PreviousNext

Related