Skip to content

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.

Output

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.

Output

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.

Output

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.

References:
Java 8 Hashtable Documentation

About the author

Leave a Reply

Your email address will not be published.