Skip to content

Sort Hashtable by Values in Java Example

This example shows how to sort Hashtable by values in Java. This example also shows how to sort Hashtable by values using the sort method of the Collections class and a custom Comparator.

How to sort the Hashtable by values in Java?

The Hashtable class in Java does not maintain the order of its entries, so even if we sort it, there is no guarantee that the elements will be returned in that order. We need to convert hashtable to a collection that maintains the element order.

How to sort Hashtable by values if you only want values?

We can get all the values from the hashtable using the values method, convert it to a List (like ArrayList or LinkedList) and then we can sort the List using the sort method of the Collections class as given below.

Output

The sort method of the Collections class sorts the list elements in their natural order, which is ascending order for the type Integer. If you want to sort the values in descending order, pass the reverse comparator in the sort method as given below.

Output

How to sort Hashtable by values if you want key-value pairs?

In the above example, we sorted only the values of the Hashtable object. What if you want to get the Map that is sorted by the hashtable values?

In that case, we need to first get all entries or mappings from the hashtable using the entrySet method and convert it to a List. Then we need to sort the list by entry value and put the sorted entries in a Map that maintains the insertion order e.g. LinkedHashMap as given below.

Output

How to sort Hashtable of custom class objects by value?

If the hashtable values are objects of a custom class, then the custom class must implement the Comparable interface. The above examples worked because the Integer class has implemented the Comparable interface.

The hashtable value custom class needs to implement the Comparable interface and define the compareTo method.

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.