fred05 fred05 - 2 months ago 7
Groovy Question

Groovy: How to sort String array of text+numbers by last digit

I have array like this:

def arr = [
"v3.1.20161004.0",
"v3.1.20161004.1",
"v3.1.20161004.10",
"v3.1.20161004.11",
"v3.1.20161004.2",
"v3.1.20161004.3",
"v3.1.20161004.30",
]


I need to get this:

def arr = [
"v3.1.20161004.0",
"v3.1.20161004.1",
"v3.1.20161004.2",
"v3.1.20161004.3",
"v3.1.20161004.10",
"v3.1.20161004.11",
"v3.1.20161004.30",
]


How to sort it by last number '.x' ?

Answer

You can tokenize each string on . and then grab the last element as an Integer, and sort on this (passing false to return a new list)

def newArray = arr.sort(false) { it.tokenize('.')[-1] as Integer }