Sort Hashtable by Keys in Java Example

This example shows how to sort hashtable by keys in Java. This example also shows how to sort Hashtable by keys using the TreeMap class.

How to sort Hashtable by keys?

The Hashtable keys can be sorted using the TreeMap. The TreeMap class in Java automatically sorts the entries using the natural ordering of the keys or by the custom comparator provided in the constructor.

We can use the TreeMap constructor to convert the hashtable to a treemap object.


How to sort Hashtable of custom class objects by keys?

Let’s try to convert a Hashtable of custom class objects to a treemap object.


If the key of the TreeMap is an object of a custom class, then the custom class either must implement the Comparable interface or a custom Comparator must be provided in the TreeMap constructor. If none of that is done, the code throws java.lang.ClassCastException: cannot be cast to java.lang.Comparable exception as we got.

Let’s implement the Comparable interface in the User class and try again.


As we can see from the output, now the TreeMap is sorted by the hashtable custom class keys.

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

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

Java 8 Hashtable Documentation

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *