Traverse a Hashtable

Traverse a Hashtable

Java hashtables are widely used to maintain a mapping relationship between objects. It is easy to store, and retrieve an object from a hashtable using an arbitrary key. Sometimes, it is useful to get an enumeration of all the keys used on a hashtable. This can be done using the keys() method of java.util.Hashtable, as in:

     java.util.Enumeration keys = aHashTable.keys();    //aHashTable is an instance of java.util.Hashtable

Having all the keys used to map objects to a hashtable, we can traverse the entire hashtable and print out key-value pairs, as in:

     while( keys.hasMoreElements() )     {        Object aKey = keys.nextElement();        Object aValue = aHashTable.get(aKey);        System.out.println("Key: ""+aKey.toString()+"" has value of: "" +aValue.toString()+""");    }

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist