以相反顺序Java对Arraylist中的数组进行排序

pro*_*666 -3 java arrays sorting arraylist

我用Arrays制作了一个Arraylist,我想按相反的顺序按照数组中的第一项进行排序.例如:

ArrayList<int[]> arr = new ArrayList<>();
arr.add[1,500,20];
arr.add[5,30,60];
arr.add[2,10,20];
Run Code Online (Sandbox Code Playgroud)

我想这样排序:

[5,30,60],[2,100,20],[1,500,300]
Run Code Online (Sandbox Code Playgroud)

Java中有没有选项可以做到这一点?我知道Comparator,但在这种情况下我不知道如何使用它.

感谢帮助

You*_*bit 5

你可以实现一个客户Comparator,并把它传递给Collections.sort()与一起ArrayList.

ArrayList<int[]> arrayList = new ArrayList<>();
arrayList.add(new int[]{1,500,20});
arrayList.add(new int[]{5,30,60});
arrayList.add(new int[]{2,10,20});

// Custom `Comparator` to sort the list of int [] on the basis of first element.
Collections.sort(arrayList, new Comparator<int[]>() {
  @Override
  public int compare(int[] a1, int[] a2) {
    return a2[0] - a1[0];  // the reverse order is define here.
  }
});

// Output to STDOUT
for(int a[] : arrayList) {
  for (int i: a){
    System.out.print(i + "\t");
  }
  System.out.println();
}
Run Code Online (Sandbox Code Playgroud)

输出:

5   30  60  
2   10  20  
1   500 20  
Run Code Online (Sandbox Code Playgroud)

免责声明:上面的代码不处理像null和的角落案件empty array (zero size).请根据您的需要适当处理.