Created
May 31, 2015 15:39
-
-
Save hablutzel1/50803efa95282bfcc531 to your computer and use it in GitHub Desktop.
Basic Comparator to compare/order Java versions, e.g. 1.7.0_79 vs 1.8.0_45
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import java.util.Comparator; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
/** | |
* Very basic comparator | |
* <p><b>Warning: it could be unstable because there are more possible patterns for Java versions | |
*/ | |
public class JavaVersionComparator implements Comparator<String> { | |
@Override | |
public int compare(String firstVersion, String secondVersion) { | |
// TODO check http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html for improved robustness | |
Pattern basicJavaVersionRegex = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)_(\\d+)"); | |
Matcher firstMatcher = basicJavaVersionRegex.matcher(firstVersion); | |
firstMatcher.find(); | |
Integer firstN1 = Integer.valueOf(firstMatcher.group(1)); | |
Integer firstN2 = Integer.valueOf(firstMatcher.group(2)); | |
Integer firstN3 = Integer.valueOf(firstMatcher.group(3)); | |
Integer firstN4 = Integer.valueOf(firstMatcher.group(4)); | |
Matcher matcher2 = basicJavaVersionRegex.matcher(secondVersion); | |
matcher2.find(); | |
Integer secondN1 = Integer.valueOf(matcher2.group(1)); | |
Integer secondN2 = Integer.valueOf(matcher2.group(2)); | |
Integer secondN3 = Integer.valueOf(matcher2.group(3)); | |
Integer secondN4 = Integer.valueOf(matcher2.group(4)); | |
int result = firstN1.compareTo(secondN1); | |
if (result != 0) return result; | |
result = firstN2.compareTo(secondN2); | |
if (result != 0) return result; | |
result = firstN3.compareTo(secondN3); | |
if (result != 0) return result; | |
return firstN4.compareTo(secondN4); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment