JavaDeveloper.co.in network has launched a dedicated site just for Java Examples. You can now learn java language by examples.
/*
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 into HashMap
hashMap.put( "Two", new Integer(2) );
hashMap.put( "Three", new Integer(3) );
System.out.println("Retriving all
keys from the HashMap");
//retrive 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
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 :
Retriving all keys from
the HashMap
Three
Two
One
*/