sfgroups
sfgroups

Reputation: 19099

Groovy String array sort using float value truncating zeros at the end

I have array of string float value, I want to sort it in the reverse order. any values ends with zero is truncating.

eg.

25.200 comes with 25.2

How to preserve the zero values?

Here is the code I have.

class Test {

    def static main(args){

        def tags = ["13.199", "14.200", "15.201", "25.220", "26.220", "3.200", "4.201", "5.201", "6.201", "7.202", "8.203", "9.205"]
        println tags.collect{it as Float}.sort{-it}
        println tags*.toFloat()?.sort()?.reverse()
        }
}

output

[26.22, 25.22, 15.201, 14.2, 13.199, 9.205, 8.203, 7.202, 6.201, 5.201, 4.201, 3.2]
[26.22, 25.22, 15.201, 14.2, 13.199, 9.205, 8.203, 7.202, 6.201, 5.201, 4.201, 3.2]

Upvotes: 0

Views: 126

Answers (1)

tim_yates
tim_yates

Reputation: 171084

To keep the zeroes, you need to keep the strings. But you need to sort by the float value (as you've seen)

One solution is to create a list for each element in your list. The first can be the float value, the second the original string

Then sort by the first element, and collect the second values

tags.collect { [ it.toFloat(), it ] }
    .sort { it[0] }
    *.getAt(1)​

Upvotes: 1

Related Questions