Privacy Policy Terms Of Use. Copyright © 2006-2010 Java Tutorials and Examples.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
- /*
- Java Iterator example.
- This Java Iterator example describes how Iterators are used with Collections.
- */
- import java.util.Iterator;
- import java.util.HashMap;
- public class IteratorExample{
- public static void main(String args[]){
- HashMap hashMap = new HashMap(); // Constructs a new empty HashMap
- hashMap.put("One", new Integer(1)); //adding value to HashMap
- hashMap.put("Two", new Integer(2));
- hashMap.put("Three", new Integer(3));
- System.out.println("Retrieving all keys from the HashMap");
- //retrieve iterator from keySet of the HashMap
- Iterator iterator = hashMap.keySet().iterator();
- /*
- Iterators hasNext() method returns true if it has more element,
- otherwise it returns false.
- Iterator's next() method returns the current element of underlying collection.
- IMPORTANT : It returns an Object, so we need to downcast it.
- */
- while(iterator. hasNext()){
- System.out.println(iterator.next());
- }
- }
- }
- /*
- OUTPUT of the above given Java Iterator Example would be:
- Retrieving all keys from the HashMap
- Three
- Two
- One
- */

Post new comment