Sort map by value using java 8 features

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:

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
https://github.com/kavitagupta972/MyWork/blob/master/Sorting%20Map.zip
Hope you find this article helpful. For more java 8 features, stay tuned….
Comments
Post a Comment