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

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


当前回答

我知道这是一个相当老的线程,但这里是一个更新版本的整数和Java 8:

Arrays.sort(array, (o1, o2) -> o2 - o1);

注意,对于正常的升序(或Comparator.comparingInt()),它是“o1 - o2”。

这也适用于任何其他类型的对象。说:

Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());

其他回答

int数组降序排序的简单方法:

private static int[] descendingArray(int[] array) {
    Arrays.sort(array);
    int[] descArray = new int[array.length];
    for(int i=0; i<array.length; i++) {
        descArray[i] = array[(array.length-1)-i];
    }
    return descArray;
}

没有显式比较器:

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

使用显式比较器:

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

不能直接使用Arrays.sort()和Collections.reverseOrder()对原语数组(即int[] arr ={1,2,3};)进行反向排序,因为这些方法需要引用类型(Integer)而不是原语类型(int)。

但是,我们可以使用Java 8 Stream首先对数组进行装箱,以倒序排序:

// an array of ints
int[] arr = {1, 2, 3, 4, 5, 6};

// an array of reverse sorted ints
int[] arrDesc = Arrays.stream(arr).boxed()
    .sorted(Collections.reverseOrder())
    .mapToInt(Integer::intValue)
    .toArray();

System.out.println(Arrays.toString(arrDesc)); // outputs [6, 5, 4, 3, 2, 1]

对于列表

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

对于数组

Arrays.sort(array, Collections.reverseOrder());

我有下面的工作解决方案

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