Skip to content

Iterate through Java Hashtable Example

This example shows how to iterate through Java Hashtable. This example also shows how to iterate through Hashtable keys, values, and entries using Iterator, Enumeration, for loop, while loop, and forEach method.

How to iterate through Hashtable in Java?

There are various ways in which we can iterate through hashtable keys, values, and entries as given below.

1. How to iterate over Hashtable keys?

We can get all the keys of the Hashtable using the keys method. It returns an enumeration of all keys contained in the hash table object. Once we get that, we can iterate through hashtable keys using the hasMoreElements and nextElement method.

Output

We can also get a Set view of all the keys contained in the hashtable using the keySet method. We can then get an Iterator for the Set and iterate using the hasNext and next methods as given below.

2. How to iterate over Hashtable values?

We can get all the values contained in the Hashtable object using the elements method. It returns an Enumeration of all the values of the hash table object. Once we get the enumeration, we can iterate through the values using the hasMoreElements and nextElement methods.

Output

We can also use the Hashtable values method that returns a Collection view of all the values contained in the hashtable object. Once we get the values collection object, we can get an iterator and iterate through it as given below.

Output

3. How to iterate over Hashtable entries (key-value mappings)?

We can get all the entries of the Hashtable using the entrySet method. Once we get a Set view of all the mappings of the hashtable object, we can iterate through the entries using below given ways.

Using Iterator

Using enhanced for loop

We can also use the enhanced for loop as given below.

Output

Using forEach

If you are using Java version 8 or later, you can also use the forEach method to iterate through hashtable entries as given below.

Output

This example is a part of the Hashtable in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Hashtable Documentation

About the author

Leave a Reply

Your email address will not be published.