我有一个arraylist,它包含double值数组,我想对行进行排序,例如按字段中的第三个值排序。
有一种聪明的方法吗? (上升/下降)
声明:
private List<double[]> row = new ArrayList<double[]>();
示例:
按第二列(asc)排序
编辑!!
以后我会尝试这个但是我没有时间去测试它!有人可以验证这个
if (sortDir == SortDirection.ASCENDING) {
Collections.sort(tabelle,new Comparator<double[]>() {
public int compare(double[] array1, double[] array2) {
return Double.compare(array1[colIds.indexOf(aColId)], array2[colIds.indexOf(aColId)]);
}
});
}
if (sortDir == SortDirection.DESCENDING) {
Collections.sort(tabelle,new Comparator<double[]>() {
public int compare(double[] array1, double[] array2) {
return Double.compare(array1[colIds.indexOf(aColId)], array2[colIds.indexOf(aColId)]);
}
});
Collections.reverse(tabelle);
}
哇太多评论:D谢谢
答案 0 :(得分:2)
在Java 8中:
public static void main(final String[] args) throws IOException {
final List<double[]> row = new ArrayList<double[]>();
row.add(new double[]{10.0, 5.0, 200.3});
row.add(new double[]{9.1, 1.4, 3.3});
row.add(new double[]{9.1, 1.4, 3.3});
final List<double[]> sorted = row.stream().
sorted((l, r) -> Double.compare(l[2], r[2])).
collect(Collectors.toList());
}
或者,如果您想进行排序:
row.sort((l, r) -> Double.compare(l[2], r[2]));
答案 1 :(得分:0)
Collections.sort()
可以Comparator
。
请参阅API。
答案 2 :(得分:0)
使用Collections.sort()
List<double[]> row = new ArrayList<double[]>();
row.add(new double[] { 10.0, 5.0, 200.3 });
row.add(new double[] { 9.1, 1.4, 3.3 });
row.add(new double[] { 1.1, 7.6, 3.4 });
Collections.sort(row, new Comparator<double[]>() {
@Override
public int compare(double[] o1, double[] o2) {
return Double.compare(o1[1],o2[1]);
}
});
答案 3 :(得分:0)
嗨我已经创建了一个获取数组列表的函数,以及要比较和缩短列表的列的位置......
public void tobeShorted(List<double[]> l, int c){ //short the list by column wise comparision
for(int i=0; i<l.size()-1; i++){ //using Bubble short Technique
double[] current1=l.get(i); //get the current array
for(int j=i+1; j<l.size(); j++){
double[] current2=l.get(j); //get the next array
if(current1[c-1]<current2[c-1]){ //compare the element of the given POSITION(not index) of arrays
l.remove(j);l.add(j, l.get(i)); //remove and add rows
l.remove(i);l.add(i, current2); //remove and add rows
}
}
}
}
我检查了它并且它正在工作,它缩短了降序中的列表......我希望它可以帮助你......!