package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("3");list.add("a1");list.add("a12");list.add("a13");list.add("a2");
list.add("a3");list.add("c1");list.add("b2");list.add("d1");
list.add("b1");list.add("c3");list.add("2");list.add("1");
System.out.println("排序前------>"+list);
Collections.sort(list, new Comparator<String>() {
String regNum = "[d]";//数字字符
String regStr = "[^d]";//非数字字符
@Override
public int compare(String o1, String o2) {
int num1 = Integer.parseInt(o1.replaceAll(regStr, ""));
int num2 = Integer.parseInt(o2.replaceAll(regStr, ""));
String str1 = o1.replaceAll(regNum, "");
String str2 = o2.replaceAll(regNum, "");
//都有字母
if( ! isnull(str1) && ! isnull(str2)){
if(str1.compareTo(str2) > 0){
return 1;
}else if(str1.compareTo(str2) < 0){
return -1;
}else{
return num1-num2;
}
}else{//存在数字
//都是数字
if(isnull(str1) && isnull(str2)){
return num1 - num2;
}else if(isnull(str1) && ! isnull(str2)){//数字排前面:o1是数字,o2不是数字
return -1;
}else if(! isnull(str1) && isnull(str2)){//数字排前面:o1不是数字,o2是数字
return 1;
}else{
return 0;
}
}
}
});
System.out.println("排序后======>"+list);
}
private static boolean isnull(String str){
return str == null || str.trim().length() == 0;
}
}