如何使用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
}
答案 0 :(得分:3)
可能只是:
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