Skip to content

Java Print HashMap Example

This example shows how to print HashMap in Java. The example also shows how to print all keys, all values, and all key-value pairs of HashMap using different ways.

How to print HashMap in Java?

The AbstractMap class, the parent class of the HashMap class, has overridden the toString method which returns a string representation of the map. All key-value pairs are enclosed in { and } and separated by a comma (,). The iterator of the entry set returns the order of the key-value pairs.

Output

How to print all keys and values of HashMap using entrySet?

If you do not want the default formatting done by the toString method, you can get the entry set from the HashMap and print all key-value pairs one by one using the for loop as given below.

Output

Java 8 and above

If you are using Java version 8 and above, you can use the below given code to print all keys and values of HashMap.

Output

How to print all the keys of HashMap?

The keySet method of the HashMap class returns a Set view containing all the keys of the HashMap.

Output

You can also use the System.out.println statement instead of using the for loop if you do not want to change the output format.

Output

How to print all the values of the HashMap?

The values method of the HashMap returns a Collection view containing all the values contained in the HashMap.

Output

You can also use System.out.println statement instead of using the for loop if you do not want to change the output format.

Output

How to print HashMap containing custom class object as keys or values?

In all of the above examples, we printed Integer and String objects using the System.out.println statement. They were printed fine because both of these classes have overridden the toString method. Let’s try to print HashMap containing custom class objects.

We have put objects of Emp class as values in the HashMap in below given example.

Output

As you can see from the output, the keys were printed fine but the values were not. It is because our Emp class has not overridden the toString method so it inherited the method from the Object class.

The toString method of the Object class returns the class name of the object, followed by @, followed by the hexadecimal hash code of the object. The format is not readable and hence it is suggested for all the subclasses to override the toString method to produce informative text.

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

Output

Now our program printed the HashMap containing custom Emp objects as the values correctly.

Tip: Always override the toString method for the objects used as either keys or values of the HashMap.

This tutorial is a part of the Java HashMap tutorial.

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

About the author

1 comments

Leave a Reply

Your email address will not be published.