Home Java SCJP SCWCD Servlet Submit News Contact Us Site Map


Over 500 magazines for free (including Oracle Magazine)!

Yes all of them are FREE. You can subscribe to ALL of them.
Click here to apply today!

JavaDeveloper.co.in network has launched a dedicated site just for Java Examples. You can now learn java language by examples.

Please visit Java Examples to get started !

/*

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

*/

For more java examples please visit Java Examples

Home Java SCJP SCWCD Servlet Site map