How to sort Hashmap by key in Java

This tutorial shows you how to sort hashmap by key in java using java.util.TreeMap. Beside it also shows how to sort a hashmap in Ascending or Descending order by key or value using a custom Comparator and Java 8 Lambda expression.

Sorted HashMap By Key Example
You sort a java.util.HashMap by putting all the entries in a java.util.TreeMap. It will be sorted automatically. Let’s look at the blow code snippet.

Output

Sorted HashMap By Key Reverse using custom comparator
You can sort a java.util.HashMap in descending order by using a custom Comparator.

Output

Sorted HashMap By Value using custom comparator
You can sort a java.util.HashMap by value by using a custom Comparator. Let’s create a custom Comparator with name ValueComparator such as:

And we can use the ValueComparator to sort a HashMap by Value.

Output

Java 8 Lambda Sorted Map By Value
It’s easy for you to sort java.util.HashMap by value in Java 8. You can just do it because Java 8 has a new streaming API on top of the collections framework.

Output

That’s it on how to sort hashmap by key in Java. I hope you can use these tips to optimize your source code and increate performace of program.

Leave a Comment

*

Please share it if you found this useful
Hide Buttons