Sorting map by value

Posted By : Pankaj Kumar Yadav | 22-Jun-2015

In this blog we will know how to sort map by it's value.


Here are the steps to sort map by value in ascending or descending order

Step-1. Let we have a map .

 

Now if we need to sort it by it's value in ascending order

 def map = [apple:3, banana:2, mongo:1]

// ascending order
map = map.sort {it.value}
println map

// output [mongo:1, banana:2, apple:3]

 

Now if we need to sort it by it's value in ascending order

// descending order
map = map.sort {a, b -> b.value <=> a.value}
println map

// output [apple:3, banana:2, mongo:1]

 >

 

THANKS

About Author

Author Image
Pankaj Kumar Yadav

Pankaj has been working as a Grails developer expertise in struts, spring, ejb, hibernate and angularjs framework.

Request for Proposal

Name is required

Comment is required

Sending message..