Easy way to sort map by value using java 8

August 04, 2019

Easy way to sort map by value using java 8

Generally, we sort the values by using keys. In case of map in java, we have a habit to sort keys, not values. But, there can be some scenarios , where we need to sort data based on values in map.

I faced this challenge while working on one of my projects, where i need to do sorting based on values in hashmap. Then, i try to search easy way to achieve that, and found the api in java to do this job.

I am excited to share with everyone , feature of java8 which makes my life easy, infact my coding life easy.

I will show you both the code, before using java 8 features, and along with java 8 features. You will see the difference.

Before java 8, code was like:

sort unsortedFruits map with comparator

Using java 8 features :

sorting using java 8 features

Code is clean and one liner to sort the map by values, not keys.

You can download and run the complete code by downloading from my github link

Hope you find this article helpful. For more java 8 features, stay tuned….

About the Author:

Kavita Gupta - She is very passionate about technology and writes blogs about technology, You can find more about her here (