Alfred Hitchkock
Alfred Hitchkock

Reputation: 365

How to compare values in groovy

I'm trying to compare the current version with available versions of a program. I want all the available versions greater than the current version. I don't know how I make this comparison:

Sample of groovy.txt:

11.6

Sampple of groovy1.txt:

9.6.3 9.6.6 9.6.8 9.6.9 9.6.11 9.6.12 9.6.16 10.14 10.14 10.16 11.4 11.6 11.7 11.8 11.9 11.11 12.4 12.6

When I do this, I am getting below error because of cast conversion in av.findAll { it > cv }:

Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String

Upvotes: 0

Views: 1153

Answers (1)

Maicon Mauricio
Maicon Mauricio

Reputation: 3001

Your problem occurs because tokenize returns a list of strings which cannot be compared to a string. It happens at this line:

av.findAll { it > cv }

For cv use:

def cv = output.tokenize().collect { it.tokenize('.').collect { it as int } }.first()

For av:

def av = output2.tokenize().collect { it.tokenize('.').collect { it as  int } }

I turned version numbers like 9.6.11 in arrays like [9, 6, 11] to compare until find out if the number is greater.

Then write the code to compare the versions:

av.findAll { 
    def isVersionGreater
    it.indexed().any { i, v ->
        if (cv[i] == v) return false
        isVersionGreater = v > (cv[i] ?: 0)
        return true
    }
    return isVersionGreater
}.collect { it.join('.') }

AFAIK, unfortunately, Groovy doesn't have a Python equivalent of [9, 6, 11] < [11, 1] to compare versions.

Upvotes: 1

Related Questions