Groovy Sort List

Trying to sort (ascending) a list of strings in a 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 on GitHub. But looking for a groovy way. Any help is appreciated.

Desired conclusion:

 f1, f2, f3, f5, f10, f12, f20, f22, f34, f50 
+5
source share
3 answers
 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] 
+1
source
 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] 
+3
source

You can also use the following comparator:

 list.sort { a,b -> a[0] <=> b[0] == 0 ? (a[1..-1] as int) <=> (b[1..-1] as int) : a[0] <=> b[0] } 

He compares literals in the first place and, when they are equal, compares the numerical part. Using this method with a list like:

 ['f3', 'f10', 'f1', 'f12', 'f2', 'f34', 'f22','f20','f50', 'f5', 'g1', 'g11', 'z0', 'a00', 'a01'] 

generates the following result:

 [a00, a01, f1, f2, f3, f5, f10, f12, f20, f22, f34, f50, g1, g11, z0] 
+1
source

Source: https://habr.com/ru/post/1271597/


All Articles