Skip to content

Instantly share code, notes, and snippets.

@atsiarenia
Created November 12, 2018 09:17
Show Gist options
  • Save atsiarenia/9e3bd6519a9d2f851fa318abd686b893 to your computer and use it in GitHub Desktop.
Save atsiarenia/9e3bd6519a9d2f851fa318abd686b893 to your computer and use it in GitHub Desktop.
Number aware string sorting with comparator
import java.math.BigInteger;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringWithNumberComparator implements Comparator<CharSequence> {
public static final StringWithNumberComparator INSTANCE =
new StringWithNumberComparator();
private static final Pattern PATTERN = Pattern.compile("(\\D*)(\\d*)");
private StringWithNumberComparator() {
}
public int compare(CharSequence charSequenceOne, CharSequence charSequenceTwo) {
Matcher matcher1 = PATTERN.matcher(charSequenceOne);
Matcher matcher2 = PATTERN.matcher(charSequenceTwo);
while (matcher1.find() && matcher2.find()) {
int nonDigitCompare = matcher1.group(1).compareTo(matcher2.group(1));
if (0 != nonDigitCompare) {
return nonDigitCompare;
}
if (matcher1.group(2).isEmpty()) {
return matcher2.group(2).isEmpty() ? 0 : -1;
} else if (matcher2.group(2).isEmpty()) {
return +1;
}
BigInteger number1 = new BigInteger(matcher1.group(2));
BigInteger number2 = new BigInteger(matcher2.group(2));
int numberCompare = number1.compareTo(number2);
if (0 != numberCompare) {
return numberCompare;
}
}
return matcher1.hitEnd() && matcher2.hitEnd() ? 0 :
matcher1.hitEnd() ? -1 : +1;
}
public static void main(String[] args) {
System.out.println(StringWithNumberComparator.INSTANCE.compare("qwe 7", "qwe 8"));
System.out.println(StringWithNumberComparator.INSTANCE.compare("qwe 8", "qwe 7"));
System.out.println(StringWithNumberComparator.INSTANCE.compare("qwe 9", "qwe 10"));
System.out.println(StringWithNumberComparator.INSTANCE.compare("qwe 20", "qwe 19"));
System.out.println(StringWithNumberComparator.INSTANCE.compare("qwe 20", "qwe 20"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment