import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sorter {
public static void main(String[] args) {
List<String> strs = new ArrayList<String>();
strs.add("aa2");
strs.add("aa100");
strs.add("aa1");
strs.add("aa10");
strs.add("aa78");
System.out.println(strs);
// 用了一个Comparetor
Comparator<String> com = new Comparator<String>() {
public int compare(String o1, String o2) {
// 前面3个IF主要是判空的
if (o1 == o2) {
return 0;
}
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
// 这里没有做太多的判断, index 代表第几个开始是数字, 直接从后面遍历
// 比如 aa11, 我们就会判断从下标[2]开始为不是数字, 就直接截取 [2] 后面, 即11
int index = 0;
for (index = o1.length() - 1; index >= 0
&& (o1.charAt(index) >= '0' && o1.charAt(index) <= '9'); index--)
;
int num1 = Integer.parseInt(o1.substring(index + 1));
for (index = o2.length() - 1; index >= 0
&& (o2.charAt(index) >= '0' && o2.charAt(index) <= '9'); index--)
;
int num2 = Integer.parseInt(o2.substring(index + 1));
return num1 - num2;
}
};
Collections.sort(strs, com);
System.out.println(strs);
}
}
温馨提示:答案为网友推荐,仅供参考