Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numeric string sorting with letters and numbers in Groovy

simple question, don't know if it gets a simple answer. Is there a way to sort a list of string wich contains letters and numbers, but considering the numbers as well?

For example, my list contains:

(1) ["Group 1", "Group2", "Group3", "Group10", "Group20", "Group30"]

(The strings doesn't have the word "group" necessarily, it could have others words)

if I sort it, it shows:

(2)
Group 1
Group 10
Group 2
Group 20
Group 3
Group 30

Is there a way to sort it like (1) ?

Thanks

like image 821
Johnny C. Avatar asked Sep 04 '12 11:09

Johnny C.


People also ask

How do you sort a string with numbers?

The split() method of the string class accepts a string representing a delimiter, splits the current string into an array of tokens. Using this method split the given string into an array of tokens. The parseInt() method of the Integer class accepts a String value and converts it into an integer.

Can we sort numbers as string?

There is no direct method to sort a string in Java. You can use Arrays, which has a method CharArray() that will create a char input string and using another method (Arrays.


1 Answers

try this:

def test=["Group 1", "Group2", "Group3", "2", "Group20", "Group30", "1", "Grape 1", "Grape 12", "Grape 2", "Grape 22"]

test.sort{ a,b ->
    def n1 = (a =~ /\d+/)[-1] as Integer
    def n2 = (b =~ /\d+/)[-1] as Integer

    def s1 = a.replaceAll(/\d+$/, '').trim()
    def s2 = b.replaceAll(/\d+$/, '').trim()

    if (s1 == s2){
        return n1 <=> n2
    }
    else{
        return s1 <=> s2
    }
}

println test

If you want to compare first the number you have to change the internal if with:

if (n1 == n2){
    return s1 <=> s2
}
else{
    return n1 <=> n2
}

This take te last number it found in the string, so you can write what do you want, but the 'index' should be the last number

like image 140
rascio Avatar answered Oct 17 '22 16:10

rascio