有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?

还是说我必须停止懒惰,自己做这件事:[


当前回答

另一种使用Comparator的方法

import java.util.Arrays;
import java.util.Comparator;
...

Integer[] aInt = {6,2,3,4,1,5,7,8,9,10};
Arrays.sort(aInt, Comparator.reverseOrder()  );

其他回答

没有显式比较器:

Collections.sort(list, Collections.reverseOrder());

使用显式比较器:

Collections.sort(list, Collections.reverseOrder(new Comparator()));

在这里加上我对几个不同场景的答案 对于数组

Arrays.sort(a, Comparator.reverseOrder());

FWIW列表

Lists.reverse(a);

任何及所有收集

Collections.reverse(a);

我有下面的工作解决方案

    public static int[] sortArrayDesc(int[] intArray){
    Arrays.sort(intArray);                      //sort intArray in Asc order
    int[] sortedArray = new int[intArray.length];   //this array will hold the sorted values

    int indexSortedArray = 0;
    for(int i=intArray.length-1 ; i >= 0 ; i--){    //insert to sortedArray in reverse order
        sortedArray[indexSortedArray ++] = intArray [i];
    }
    return sortedArray;
}

Java 8:

Arrays.sort(list, comparator.reversed());

更新: Reversed()反转指定的比较器。通常比较器的顺序是升序的,所以这将顺序改为降序。

我不知道你的用例是什么,但是除了这里的其他答案之外,另一个(惰性)选项是仍然按照你指出的升序排序,但然后以反向顺序迭代。