Skip to content

Print Hashtable in Java Example

This example shows how to print Hashtable in Java. This example also shows how to print Hashtable keys, values, or entries in the console using an iterator, for loop, and forEach method.

How to print Hashtable in Java?

The simplest way to print the hashtable in the console or to the log file is by using the toString method. The Hashtable class has overridden the toString method from the Object class. It returns a string representation of all entries stored in the hashtable enclosed by “{” and “}” and separated by “, “.

Output

There are various ways using which we can print hashtable keys, values or entries as given below.

How to print all the keys of the Hashtable?

1. Using the keys method

Get enumeration of all keys of the Hashtable and print them one by one.

Output

2. Using the keySet method

We can get the Set view of all the keys contained in the hashtable using the keySet method. We can then iterate and print them using an iterator.

Output

How to print all the values of the Hashtable?

1. Using the elements method

The elements method returns an enumeration of all the values of the Hashtable object.

Output

2. Using the values method

The values method returns a Collection view of all values of the hash table object.

Output

How to print all the entries or mappings of the Hashtable?

We can get a Set view of all the entries or mappings of hashtable using the entrySet method. We can then iterate through hashtable entries using below given ways.

1. Using an Iterator

Output

2. Using the enhanced for loop

Output

3. Using the forEach

We can also use the forEach method to print hashtable mappings (for Java version 8 and later).

Output

How to print Hashtable of custom class objects?

When we print hashtable containing custom class objects in console, it does not produce useful information as shown in below example.

Output

Since the User class has not overridden the toString method, the toString method inherited from the Object class is called that prints object information in “className@objectHashCode” format.

Let’s override the toString method in the User class and try again.

Output

This example is a part of the Java Hashtable 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.