Skip to content

Java Print TreeMap Example

This example shows how to print TreeMap in Java. The example also shows how to print all keys, all values, and all entries of TreeMap using for loop and iterator.

How to print TreeMap in Java?

There are several ways using which you can print TreeMap keys, values and entries as given below.

1. How to print all the keys of TreeMap?

First, get all the keys of the TreeMap using the keySet method and then use the for loop to iterate and print them.

You can also use an Iterator as given below.

Output

2. How to print all the values of TreeMap?

First, get all the values of the TreeMap using the values method and then use the for loop to iterate and print them.

You can also use an iterator as given below.

Output

3. How to print all the entries of TreeMap?

Get all the entries of the TreeMap using the entrySet method and then use the for loop to iterate and print them.

You can also use an iterator as given below.

Output

4. How to print TreeMap having custom class objects as keys or values?

Let’s first see an example of printing a TreeMap object having objects of a custom class Emp as values.

Output

Well, it did not print any useful information at all. The reason is our Emp class has not overridden the toString method from the Object class. In that case, the toString method of the Object class is used which prints “class_name@object_hashcode” when an object is printed.

To fix this, we need to override the toString method in our Emp class. Let’s do that and try again.

Output

As you can see from the output, this time it printed the useful information.

Tip: Always override the toString method in your custom classes.

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

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

References:
Java 8 TreeMap

About the author

Leave a Reply

Your email address will not be published.