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.7 (9 votes)
Share this
Anonymous's picture

I was hoping to see an

I was hoping to see an example of the needed downcast
javabuddy's picture

Nice article , just to add

Nice article , just to add the functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. to read more see here difference between iterator and enumeration
Anonymous's picture

nice example.

nice example.
Anonymous's picture

I see Iterator similar to

I see Iterator similar to ArrayList.Who can explain difference between Iterator and ArrayList for me?Thanks a lot
Anonymous's picture

Collection and Iterator is

Collection and Iterator is two different thing, Iterator is used to navigate objects from collection e.g. ArrayList, HashSet etc. for more information check What is Iterator in Java

Post new comment