Reputation: 947
Sorry if this is a straight forward thing, I'm new to Groovy. I'm trying to figure out how to sort this list on the "uses" key in each sub list, but I can't seem to get it figured out:
[[name:foo, uses:2], [name:bar, uses:1], [name:baz, uses:4]]
I'm hoping to get the following result:
[[name:baz, uses:4], [name:foo, uses:2], [name:bar, uses:1]]
Does someone out there know how to best handle this? I checked similar questions but couldn't find anything pertaining to Groovy.
Thanks in advance.
Upvotes: 0
Views: 3293
Reputation: 2219
just wanted to add a shorter version
[[name:'foo', uses:2], [name:'bar', uses:1], [name:'baz', uses:4]].sort{-it.uses}
Upvotes: 3
Reputation: 57192
The easiest way to do it would be to use the sort
method
def sorted = lists.sort( {a, b -> b["uses"] <=> a["uses"] } )
sorted.each {
println it
}
// prints
// [name:baz, uses:4]
// [name:foo, uses:2]
// [name:bar, uses:1]
Upvotes: 5
Reputation: 947
I think I figured it out...
sort{a,b -> b['uses'] <=> a['uses']}
...seems to do the trick.
Upvotes: 3