我有ArrayList<ArrayList<String>>
个数据列表。我想通过多个字段对列表进行排序。如果我知道排序字段的数量,我没有问题。例如,如果我想按字段排序,其索引位于此位置(3,2,5)。示例在此处:
public int compare(List<String> rowData1, List<String> rowData2) {
String[] arr = { "2", "3", "4", "1" };
String s1 = rowData1.get(Integer.parseInt(arr[0]));
String s2 = rowData2.get(Integer.parseInt(arr[0]));
int comp = s1.compareTo(s2);
if (comp != 0) {
result = comp;
} else {
String z1 = rowData1.get(Integer.parseInt(arr[1]));
String z2 = rowData2.get(Integer.parseInt(arr[1]));
int comp1 = z1.compareTo(z2);
if (comp1 != 0) {
result = comp1;
} else {
String c1 = rowData1.get(Integer.parseInt(arr[2]));
String c2 = rowData2.get(Integer.parseInt(arr[2]));
int comp2 = c1.compareTo(c2);
if (comp2 != 0) {
result = comp2;
} else {
String b1 = rowData1.get(Integer.parseInt(arr[3]));
String b2 = rowData2.get(Integer.parseInt(arr[3]));
result = b1.compareTo(b2);
}
}
}
}
我想拥有动态(可配置)数组。等待你的建议。
答案 0 :(得分:1)
我的意思是这样的:
public class Cumpare implements Comparator<List<String>> {
private final int[] indexes;
public Cumpare(final int[] indexes) {
this.indexes = indexes;
}
@Override
public int compare(final List<String> o1, final List<String> o2) {
int value = 0;
for(int i : indexes){
value = o1.get(i).compareTo(o2.get(i));
if (value!=0) break;
}
return value;
}
}