How to sort HashMap in java by keys and values

HashMap does not preserve order of element but what if you want to sort it by keys or values. In this post, we will see how to sort HashMap by keys or values.

Java HashMap tutorial:

Sorting by Keys:

Sorting by keys can be easily done using TreeMap. You just need to pass HashMap to the constructor of TreeMap.

Sorting by values:

We can use Comparator to sort it by values.

Sorting by Keys example :

Create as below. It should implement Comparable interface

Create as below:

When you run program, you will get below output:

Sorting by values example:

Here we will sort HashMap by its values. Here I am taking HashMap to make example simpler.

When you run above program, you will get below output


  1. Extract key set from HashMap using keySet() method.
  2. Create ArrayList from above set
  3. Sort above ArrayList using Comparator
  4. Create LinkedHashMap from Sorted list

Add Comment