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
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.
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With