Version String Numeric Compare

Splitting on dots and comparing each segment numerically fixes version ordering: 1.9 sorts before 1.10, which plain string comparison gets wrong.

JavaData Integrity

Code

snippet
import java.util.List;

public class ReleaseOrdering {

    // 版本号按 numeric 数值段比较:字符串字典序会把 1.9 排到 1.10 后面
    static int compareVersions(String a, String b) {
        String[] left = a.split("\\.");
        String[] right = b.split("\\.");
        for (int i = 0; i < Math.max(left.length, right.length); i++) {
            int l = i < left.length ? Integer.parseInt(left[i]) : 0;
            int r = i < right.length ? Integer.parseInt(right[i]) : 0;
            if (l != r) {
                return Integer.compare(l, r);
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        List.of("1.10.0", "1.9.2", "1.9.10", "2.0.0").stream()
                .sorted(ReleaseOrdering::compareVersions)
                .forEach(v -> System.out.println("ordered: " + v));

        System.out.println("compare 1.9 vs 1.10 = " + compareVersions("1.9", "1.10"));
    }
}

Behavior at a glance

Under the hood: the class ReleaseOrdering and the functions compareVersions and main.

The file repeats itself only inside for (int i = 0; i < Math.max(left.length, right.length); i++). The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Putting it to use

Entry signature: static int compareVersions(String a, String b)

Output lines are prefixed (ordered:, compare 1.9 vs 1.10 =), so you can tell which step produced each line.

The sequence compareVersions lives in main; running the file triggers it.

Core lines

return Integer.compare(l, r);
List.of("1.10.0", "1.9.2", "1.9.10", "2.0.0").stream()
        .sorted(ReleaseOrdering::compareVersions)
        .forEach(v -> System.out.println("ordered: " + v));

Interactive Tools for This Topic

FAQ

What does Version String Numeric Compare print when run?
The script runs standalone; its 2 labeled outputs include `ordered:`, `compare 1.9 vs 1.10 =`.