What you said above is correct. The key is to remove the numbers in front of the string. Maybe you are not familiar with regular expressions at the moment, so I will write a simple method to remove the numbers in front of the string:
import java.util.*;
public class Main {
// 取出字符串前面的数字
public static String getStartDigits(String str) {
int len = str.length();
int stopPos = 0;
for (int i = 0; i < len; i++) { // 遍历 str 的字符
char ch = str.charAt(i);
if (!(ch >= '0' && ch <= '9')) { // 如果当前字符不是数字
stopPos = i;
break;
}
}
return str.substring(0, stopPos);
}
public static void sortByStartDigits(List<String> list) {
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
int num1 = Integer.parseInt(getStartDigits(s1));
int num2 = Integer.parseInt(getStartDigits(s2));
return num1 - num2;
}
});
}
public static void main(String[] args) throws Exception {
List<String> list = Arrays.asList(
"1号摄像机", "10号摄像机", "2号摄像机", "20号摄像机", "30号摄像机", "31号摄像机");
System.out.println("排序前:");
System.out.println(list);
sortByStartDigits(list);
System.out.println("排序后:");
System.out.println(list);
}
}
What you said above is correct. The key is to remove the numbers in front of the string. Maybe you are not familiar with regular expressions at the moment, so I will write a simple method to remove the numbers in front of the string:
Just customize one
Comparator
.