Skip to content

Instantly share code, notes, and snippets.

@j4rv
Last active February 7, 2018 09:43
Show Gist options
  • Save j4rv/d90d4c27a60ab7780b8e791b5a60f0f9 to your computer and use it in GitHub Desktop.
Save j4rv/d90d4c27a60ab7780b8e791b5a60f0f9 to your computer and use it in GitHub Desktop.
Version Strings Comparator for Java
import java.util.Comparator;
/**
* Both arguments need to be version Strings, formatted like "7.5.3", "2.3" "8.0.0.42"...
*
* If a version has more number length, it could be considered newer. Examples:
* "2.5" vs "2.5.1" -> a is older -> Negative int returned
* "2.6" vs "2.5.1" -> a is newer -> Positive int returned
* "2.5" vs "2.5.0" -> equal -> Zero returned
*
* @return a positive int if A is newer than B, a negative int if A is older than B or zero if they are equal.
*/
public class VersionStringComparator implements Comparator<String> {
private final static int NEWER = 1;
private final static int EQUAL = 0;
private final static int OLDER = -1;
private final static String versionStringRegex = "^\\d+(?:\\.\\d+)*$";
private final static String versionStringNumberSeparator = "\\.";
@Override
public int compare(String a, String b) {
Integer nullChecks = nullChecks(a, b);
if (nullChecks != null) return nullChecks; // One or both arguments are null
assert a.matches(versionStringRegex);
assert b.matches(versionStringRegex);
String[] splittedA = a.split(versionStringNumberSeparator);
String[] splittedB = b.split(versionStringNumberSeparator);
int maxLen = Math.max(splittedA.length, splittedB.length);
for(int i=0; i<maxLen; i++){
int intA = getIntValueFromSplittedVersion(splittedA, i);
int intB = getIntValueFromSplittedVersion(splittedB, i);
if(intA != intB){
return intA - intB;
}
}
return EQUAL;
}
private Integer nullChecks(String a, String b){
if (a == null && b == null) return EQUAL;
else if (a == null) return OLDER;
else if (b == null) return NEWER;
else return null;
}
private int getIntValueFromSplittedVersion(String[] splitted, int index){
if(index < splitted.length)
return Integer.parseInt(splitted[index]);
else return 0; // return 0 for cases like "2.3.0" vs "2.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment