Derrops
Derrops

Reputation: 8117

Most concise way of comparing versions in Java

Let's say I have a version of the form of major.minor.patch, e.g. 1.2.3, and I want to compare it to another version 1.1.5, as 2 > 1 the first version is greater than the second. How can I write the most concise & efficient compare function for the class Version:

class Version implements Comparable<Version> {

    int major
    int minor
    int patch

    @Override
    int compareTo(Version otherVersion) {
        // ... TODO
    }
}

Answers can be in Java or Groovy.

Upvotes: 0

Views: 392

Answers (2)

daggett
daggett

Reputation: 28564

groovy variant

@groovy.transform.ToString
class Version implements Comparable<Version> {

    int major
    int minor
    int patch

    @Override
    int compareTo(Version other) {
        major<=>other.major ?: minor<=>other.minor ?: patch<=>other.patch
    }
}

def v0=new Version(major:1,minor:2,patch:11)
def v1=new Version(major:1,minor:2,patch:22)
def v2=new Version(major:1,minor:2,patch:33)

assert v1.compareTo(v0)==1
assert v1.compareTo(v2)==-1
assert v1.compareTo(v1)==0

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201439

I would suggest adding getters for your three fields, then a Comparator using chained comparing functions. Like,

public int getMajor() {
    return major;
}

public int getMinor() {
    return minor;
}

public int getPatch() {
    return patch;
}

private static final Comparator<Version> COMP = Comparator
        .comparingInt(Version::getMajor)
        .thenComparingInt(Version::getMinor)
        .thenComparingInt(Version::getPatch);

@Override
public int compareTo(Version otherVersion) {
    return COMP.compare(this, otherVersion);
}

Upvotes: 3

Related Questions