Sorting a Map by value with Groovy is very simple, due to the added ’sort’ method on the Map interface.
def map = [a:3, b:2, c:1]
map = map.sort {it.value}
assert map == [c:1, b:2, a:3]
Turns out doing a reverse sort on a Map by values is almost as easy.
def map = [a:1, b:2, c:3]
map = map.sort {a, b -> b.value <=> a.value}
assert map == [c:3, b:2, a:1]
Using the spaceship operator (‘< =>‘) you can define a very terse syntax for accessing ‘compareTo’, as long as the values in the map implement Comparable that is.
Nice!
Related posts:





January 13th, 2010 at 8:02 am
Not sure exactly what you mean here Keegan…
The sort method returns a new Map instead of sorting the existing map – perhaps that’s what you’re seeing if you’re still examining the original Map?
Adding some println’s to the code above I see these results:
Sorting by key before sort – a:3, b:2, c:1
Sorting by key after sort – c:1,b:2,a:3
Sorting by value before sort – a:1, b:2, c:3
Sorting by value after sort – c:3,b:2,a:1
[Reply]