如何根据 groovy 中的数字对字母数字进行排序?
How to sort alphanumeric based on number in groovy?
如何使用 groovy 根据数值对字母数字值进行排序?例如:我有值列表 [NAC-1,MAK-4,NAC-5,LOP-2,MAK-3, ...]
我想从列表(NAC-5)中获取最高值。想要根据数值对列表进行排序。请指教
我正在尝试下面的代码
List1.sort{ a,b ->
def n1 = (a =~ /\d+/)[-1] as Integer
def n2 = (b =~ /\d+/)[-1] as Integer
}
可能只是:
def l = ['NAC-1','MAK-4','NAC-5','LOP-2','MAK-3',]
l.sort{ a,b -> -(((a =~ /\d+/)[-1] as Integer) <=> ((b =~ /\d+/)[-1] as Integer))
}
或者(更容易阅读):
def l = ['NAC-1','MAK-4','NAC-5','LOP-2','MAK-3',]
l.sort { a, b ->
(a,b) = [a, b].collect { (it =~ /\d+/)[-1] as Integer }
b <=> a
}
或者(非常容易阅读,@dmahapatro):
l.sort { - ( it[-1] as Integer ) } // will work for single digit number only
如何使用 groovy 根据数值对字母数字值进行排序?例如:我有值列表 [NAC-1,MAK-4,NAC-5,LOP-2,MAK-3, ...] 我想从列表(NAC-5)中获取最高值。想要根据数值对列表进行排序。请指教
我正在尝试下面的代码
List1.sort{ a,b ->
def n1 = (a =~ /\d+/)[-1] as Integer
def n2 = (b =~ /\d+/)[-1] as Integer
}
可能只是:
def l = ['NAC-1','MAK-4','NAC-5','LOP-2','MAK-3',]
l.sort{ a,b -> -(((a =~ /\d+/)[-1] as Integer) <=> ((b =~ /\d+/)[-1] as Integer))
}
或者(更容易阅读):
def l = ['NAC-1','MAK-4','NAC-5','LOP-2','MAK-3',]
l.sort { a, b ->
(a,b) = [a, b].collect { (it =~ /\d+/)[-1] as Integer }
b <=> a
}
或者(非常容易阅读,@dmahapatro):
l.sort { - ( it[-1] as Integer ) } // will work for single digit number only