[英]Sorting two dimensional array by more than one rule for each column
I have a two dimensional array and I want to sort it based on n criterias on different columns. 我有一个二维数组,我想根据不同列上的n个条件对它进行排序。 This is an example:
这是一个例子:
ID Name GPA
1 John 3.4
2 John 3.7
3 Aaron 3.0
Lets say I want to sort first by name then GPA it should show: 可以说我想先按名称排序,然后显示GPA:
ID Name GPA
3 Aaron 3.0
2 John 3.7
1 John 3.4
I have the following code so far to sort it by one rule only: 到目前为止,我只有以下代码可以仅按一条规则对其进行排序:
Arrays.sort(a, new Comparator<String[]>() {
@Override
public int compare(String[] entry1, String[] entry2) {
String time1 = entry1[n]; \\ n is provided column number
String time2 = entry2[n];
try {
double d1 = Double.parseDouble(time1);
double d2 = Double.parseDouble(time2);
return (int) (d1 - d2);
}
catch (Exception e) {
return time1.compareTo(time2);
}
}
});
where a is my two dimensional array.. my question is, how can I sort by more than one rule? 我的二维数组在哪里。我的问题是,如何按多个规则排序? and the number of rules isnt constant as the user would provide it.
规则的数量不是用户提供的常数。
how can I sort by more than one rule?
如何按多个规则排序? and the number of rules isnt constant as the user would provide it
规则的数量不是用户提供的常数
Provide a Comparator
for each column. 为每列提供一个
Comparator
器。
Then you can use the Group Comparator to combine 2 or more Comparators
into a single Comparator
so you can mix and match however you desire. 然后,您可以使用组比较器将2个或多个
Comparators
为一个Comparator
以便您可以随意混合和匹配。
You're on the right lines with your Comparator<String[]>
. 您在
Comparator<String[]>
的右边。
You can compose Comparator
s with .thenComparing()
, so you could do: 您可以使用
.thenComparing()
组成Comparator
,因此您可以执行以下操作:
Comparator<String[]> byName = Comparator.comparing( row -> row[1] );
Comparator<String[]> byGPA = Comparator.comparing( row -> Double.parseDouble(row[2]) );
Arrays.sort(a, byName.thenComparing(byGPA));
Actually you can do this more compactly with: 实际上,您可以使用以下方法更紧凑地执行此操作:
Arrays.sort(a, Comparator.comparing( row -> row[1] )
.thenComparing( row -> Double.parseDouble(row[2])));
Working with user input, composition like this is ideal - compose at runtime based on what the user inputs. 使用用户输入,这样的合成是理想的-在运行时根据用户输入进行合成。
I think it would be easier for you if you consider a list of objects instead of a two dimentional array. 我认为,如果您考虑对象列表而不是二维数组,则对您来说会更容易。
Then you can make your object Comparable 然后,您可以使对象可比
public class Person implements Comparable {
private Integer id;
private String name;
private String gpa;
...
@Override
public int compareTo(Person p) {
// TODO Define how to compare two person
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.