fred05
fred05

Reputation: 53

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' ?

Upvotes: 1

Views: 2561

Answers (2)

Cavaz
Cavaz

Reputation: 3119

When sorting an array you can define a sorting closure. In this case you can split on the dot and sort using the spaceship operator:

arr.sort { a, b -> a.tokenize('.').last().toInteger() <=> b.tokenize('.').last().toInteger() }

Upvotes: 2

tim_yates
tim_yates

Reputation: 171084

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 }

Upvotes: 3

Related Questions