user3767481
user3767481

Reputation: 327

Understanding a piece of code to use for a different scenario

Can someone explain how this piece of code works:

enum MyStringComparator implements Comparator<String> {
    INSTANCE;

    @Override
    public int compare(String s1, String s2) {
        int n1 = Integer.parseInt(s1.split("\\.")[2]);
        int n2 = Integer.parseInt(s2.split("\\.")[2]);
        return Integer.compare(n1, n2);
    }
}

I am trying to sort

"7.0.x",
"14.0.x",
"13.0.x-version_4",

So from my understanding I would want to split at the x and see what is before that?

Therefore I have tried the following:

enum MyStringComparator implements Comparator<String> {
    INSTANCE;

    @Override
    public int compare(String s1, String s2) {
        int n1 = Integer.parseInt(s1.split("\\.\\.x")[5]);
        int n2 = Integer.parseInt(s2.split("\\.\\.x")[5]);
        return Integer.compare(n1, n2);
    }
}

Which did not work since I got a number format exception. I believe I am just not understanding what the code does.

Upvotes: 0

Views: 46

Answers (1)

C. K. Young
C. K. Young

Reputation: 223023

The first piece of code looks at the third component of each string, after splitting by dots, then turns them into integers, and compares them.

In your case, though, since the third component is x, which is not a number, this won't work. If you want to compare the first two components, you'd have to do something like:

String[] parts1 = s1.split("\\.");
String[] parts2 = s2.split("\\.");
int comparison = Integer.compare(Integer.parseInt(parts1[0]), Integer.parseInt(parts2[0]));
if (comparison == 0) {
    comparison = Integer.compare(Integer.parseInt(parts1[1]), Integer.parseInt(parts2[1]));
}
return comparison;

If you're using Guava, then do this:

String[] parts1 = s1.split("\\.");
String[] parts2 = s2.split("\\.");
return ComparisonChain.start()
        .compare(Integer.parseInt(parts1[0]), Integer.parseInt(parts2[0]))
        .compare(Integer.parseInt(parts1[1]), Integer.parseInt(parts2[1]))
        .result();

Upvotes: 1

Related Questions