Warning: Creating default object from empty value in /home/kellyrob/kellyrob99.com/blog/wp-content/plugins/search-unleashed/models/incoming-search.php on line 27

The Kaptain on … stuff

24 Oct, 2009

Groovy reverse map sort done easy

Posted by: Kelly Robinson In: Development

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 == 1

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 == 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!

Share

About

Tales of development, life and the folly that goes along with both.

Tags

profile for TheKaptain at Stack Overflow, Q&A for professional and enthusiast programmers
Get Adobe Flash player