專案需對格式為 a_b_c_d 的字串進行多層級排序,編寫一個通用 Comparator 實現:優先比對第一欄位,相等則遞歸比對後續欄位,全數值轉換比較。
TestComparatorimport java.util.Comparator;
public class TestComparator implements Comparator {
public int compare(Object arg0, Object arg1) {
String[] strF = ((String) arg0).split("_");
String[] strL = ((String) arg1).split("_");
int len = strF.length;
if (len == 1) {
return Integer.parseInt(strF[0]) - Integer.parseInt(strL[0]);
}
for (int i = 0; i < len; i++) {
if (!strF[i].equals(strL[i])) {
return Integer.parseInt(strF[i]) - Integer.parseInt(strL[i]);
} else {
String strNF = getSubValue(strF, i);
String strNL = getSubValue(strL, i);
return compare(strNF, strNL); // 遞歸比對剩餘欄位
}
}
return 0;
}
private String getSubValue(String[] arr, int start) {
StringBuilder sb = new StringBuilder();
for (int i = start + 1; i < arr.length; i++) {
if (sb.length() > 0) sb.append('_');
sb.append(arr[i]);
}
return sb.toString();
}
}
public class Test {
public static void main(String[] args) {
String[] data = {"2_2_107_11","4_1_3_8","1_1_103_3","1_2_103_2",
"1_1_105_1","2_1_107_5","2_2_107_6","3_1_107_4","2_1_107_10"};
Arrays.sort(data, new TestComparator());
for (String s : data) System.out.println(s);
}
}
1_1_103_3 1_1_105_1 1_2_103_2 2_1_107_5 2_1_107_10 2_2_107_6 2_2_107_11 3_1_107_4 4_1_3_8
String.compareTo。