Java 比较器按多于一个字段排序,字段计数应该是动态的
Java Comparator sort by more then one field, count of field should be dynamically
我有 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);
}
}
}
}
我想要动态(可配置)数组。等待您的建议。
我的意思是这样的:
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;
}
}
我有 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);
}
}
}
}
我想要动态(可配置)数组。等待您的建议。
我的意思是这样的:
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;
}
}