Monday, January 10, 2011

Groovy: Sorting a Map by Values

Here's a real quick Groovy snippet demonstrating one way to sort a Map by the values stored in its entries (mostly so I don't forget how to do it):

def map = ["ghi":6, "abc":4 ,"def":5]
def sortedByValue = map.sort { a,b -> a.value <=> b.value }
println sortedByValue.keySet()
The output from this snippet is:
[abc, def, ghi]
Anyone have any other methods for doing the same thing?

1 comment: