gpt4 book ai didi

Java比较器按多个字段排序,字段计数应该是动态的

转载 作者:行者123 更新时间:2023-12-01 11:57:35 25 4
gpt4 key购买 nike

我有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;
}
}

关于Java比较器按多个字段排序,字段计数应该是动态的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28316081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com