Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java Iterator Example

  1. /*
  2. Java Iterator example.
  3. This Java Iterator example describes how Iterators are used with Collections.
  4. */
  5.  
  6. import java.util.Iterator;
  7. import java.util.HashMap;
  8.  
  9. public class IteratorExample{
  10.    
  11.     public static void main(String args[]){
  12.    
  13.         HashMap hashMap = new HashMap(); // Constructs a new empty HashMap
  14.        
  15.         hashMap.put("One", new Integer(1)); //adding value to HashMap        
  16.         hashMap.put("Two", new Integer(2));        
  17.         hashMap.put("Three", new Integer(3));
  18.        
  19.         System.out.println("Retrieving all keys from the HashMap");
  20.        
  21.         //retrieve iterator from keySet of the HashMap        
  22.         Iterator iterator = hashMap.keySet().iterator();
  23.        
  24.         /*
  25.        
  26.         Iterators hasNext() method returns true if it has more element,        
  27.         otherwise it returns false.
  28.        
  29.         Iterator's next() method returns the current element of underlying collection.
  30.        
  31.         IMPORTANT : It returns an Object, so we need to downcast it.
  32.        
  33.         */
  34.        
  35.         while(iterator. hasNext()){        
  36.             System.out.println(iterator.next());    
  37.         }
  38.    
  39.     }
  40.  
  41. }
  42.  
  43. /*
  44. OUTPUT of the above given Java Iterator Example would be:
  45. Retrieving all keys from the HashMap
  46. Three
  47. Two
  48. One
  49. */
Your rating: None Average: 3.8 (12 votes)
Share this