How to sort HashMap in java by keys and values

Previous
Next

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 Country.java as below. It should implement Comparable interface

Create TreeMapCompMain.java 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.
Example:

When you run above program, you will get below output

Explanation:

  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

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog