Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list in natural order in Groovy

Trying to sort(ascending order) the list of strings in natural / human readable order. Something like below.

def list = ['f3', 'f10', 'f1', 'f12', 'f2', 'f34', 'f22','f20','f50', 'f5']
list.sort()

I could find sample java code in GitHub. But looking for groovy way. Any help is appreciated.

Desired output:

f1, f2, f3, f5, f10, f12, f20, f22, f34, f50
like image 373
Rao Avatar asked Sep 07 '17 10:09

Rao


People also ask

How do I sort a map in groovy?

Maps don't have an order for the elements, but we may want to sort the entries in the map. Since Groovy 1.7. 2 we can use the sort() method which uses the natural ordering of the keys to sort the entries. Or we can pass a Comparator to the sort() method to define our own sorting algorithm for the keys.


2 Answers

def list = ['f3', 'f10', 'f1', 'f12', 'f2', 'f34', 'f22','f20','f50', 'f5', 'f9']
list.sort { it[1..-1] as int }​

Results:

[f1, f2, f3, f5, f9, f10, f12, f20, f22, f34, f50]
like image 127
dmahapatro Avatar answered Sep 28 '22 11:09

dmahapatro


def list = ['f3', 'f10', 'f1', 'f12', 'f2', 'f34', 'f22','f20','f50', 'f5']
list.collect{ (it=~/\d+|\D+/).findAll() }.sort().collect{ it.join() }

Result:

[f1, f2, f3, f5, f10, f12, f20, f22, f34, f50]
like image 23
daggett Avatar answered Sep 28 '22 13:09

daggett