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

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


当前回答

Java 8:

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

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

其他回答

首先,你需要使用以下命令对数组进行排序:

Collections.sort(myArray);

然后你需要使用以下命令将升序颠倒为降序:

Collections.reverse(myArray);

我有下面的工作解决方案

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

没有显式比较器:

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

使用显式比较器:

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

另一种选择可能是(对于数字!!)

将数组乘以-1 排序 再乘以-1

从字面上说:

array = -Arrays.sort(-array)

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