我在使用升序对 ArrayList 进行排序时遇到问题。我正在使用 Collection 类的 Comparator 和 Collator。如何实现预期的排序顺序?非常感谢您的帮助。
算法计算的升序为:
[AutomationRejectNotification|,AutomationRejectNotification1011, AutomationRejectNotification1021,AutomationTestNotification1, AutomationTestNotification100,AutomationTestNotification2,testDisplay Template, Testing Chrome, Testing Field, Test Notfication, testnotif, Test Notification #1]
预期升序排序为:
[AutomationRejectNotification1011, AutomationRejectNotification1021, AutomationRejectNotification|,AutomationTestNotification1, AutomationTestNotification2,AutomationTestNotification100,Test Notfication, Test Notification #1, testDisplay Template, Testing Chrome, Testing Field, testnotif]
Java代码:
public static void listSort(List<String> o1, boolean order) {
final Pattern p = Pattern.compile("^\\d+");
Comparator<String> c = new Comparator<String>() {
public int compare(String object1, String object2) {
Collator collator = Collator.getInstance(Locale.US);
Matcher m = p.matcher(object1);
if (!m.find()) {
return collator.compare(object1, object2);
} else {
Long number2 = null;
Long number1 = Long.parseLong(m.group());
m = p.matcher(object2);
if (!m.find()) {
return collator.compare(object1, object2);
} else {
number2 = Long.parseLong(m.group());
int comparison = number1.compareTo(number2);
if (comparison != 0) {
return comparison;
} else {
return collator.compare(object1, object2);
}
}
}
}
};
o1.sort(c);