Java Version Compare versionCompare(final String current, final String remote)

Here you can find the source of versionCompare(final String current, final String remote)

Description

Compares two version strings component-wise.

License

Open Source License

Parameter

Parameter Description
current the source version string
remote the target version string to compare against

Return

-1, 0 or 1 as the specified current version string is less than, equal to or greater than the specified target version string

Declaration

public static int versionCompare(final String current, final String remote) 

Method Source Code

//package com.java2s;
/*/* ww w .j  a v a 2s  . c om*/
Copyright 2015 Google Inc. All Rights Reserved.
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

public class Main {
    /**
     * Compares two version strings component-wise. Use to compare componentized version strings like
     * "3.2.2 beta 1" and "10.1". Both strings are split using the regular expression "\\.|-|\\s+".
     * 
     * @param current the source version string
     * @param remote the target version string to compare against
     * @return -1, 0 or 1 as the specified current version string is less than, equal to or greater
     *         than the specified target version string
     */
    public static int versionCompare(final String current, final String remote) {
        final String[] curComp = current.trim().split("\\.|-|\\s+");
        final String[] remComp = remote.trim().split("\\.|-|\\s+");
        int result = 0;
        for (int i = 0; (result == 0) && (i < Math.min(curComp.length, remComp.length)); i++) {
            try {
                // Try numerical comparison first
                result = Integer.parseInt(curComp[i]) - Integer.parseInt(remComp[i]);
            } catch (final NumberFormatException e) {
                // Fall back to lexical comparison (for version components
                // like "beta")
                result = curComp[i].compareToIgnoreCase(remComp[i]);
            }
        }

        // Clamp result to -1, 0 and 1 respectively
        return result < -1 ? -1 : (result > 1 ? 1 : result);
    }
}

Related

  1. versionCompare(int... args)
  2. versionCompare(String firstVersionString, String secondVersionString)
  3. versionCompare(String fromVersion, String toVersion)
  4. versionCompare(String str1, String str2)