Here is a self-contained example on how to do this (not particularly optimized):
final Pattern p = Pattern.compile("^\d+");
String[] examples = {
"1some", "2some", "20some", "21some", "3some", "some", "1abc", "abc"
};
Comparator<String> c = new Comparator<String>() {
@Override
public int compare(String object1, String object2) {
Matcher m = p.matcher(object1);
Integer number1 = null;
if (!m.find()) {
return object1.compareTo(object2);
}
else {
Integer number2 = null;
number1 = Integer.parseInt(m.group());
m = p.matcher(object2);
if (!m.find()) {
return object1.compareTo(object2);
}
else {
number2 = Integer.parseInt(m.group());
int comparison = number1.compareTo(number2);
if (comparison != 0) {
return comparison;
}
else {
return object1.compareTo(object2);
}
}
}
}
};
List<String> examplesList = new ArrayList<String>(Arrays.asList(examples));
Collections.sort(examplesList, c);
System.out.println(examplesList);
Output
[1abc, 1some, 2some, 3some, 20some, 21some, abc, some]
Explanation
- The example uses a constant
Pattern
to infer whether a number is in the String
's starting position.
- If not present in the first
String
, it compares it as is to the second.
- If present indeed in the first, it checks the second.
- If not present in the second, it compares the two
String
s as is, again
- If present in both, it compares the
Integer
s instead of the whole String
s, hence resulting in a numerical comparison rather than a lexicographical one
- If the number compare identical, it goes back to lexicographic comparison of the whole
String
s (thanks MihaiC for spotting this one)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…