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

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


当前回答

当一个数组是Integer类的类型时,你可以使用下面的方法:

Integer[] arr = {7, 10, 4, 3, 20, 15};
Arrays.sort(arr, Collections.reverseOrder());

当一个数组是int类型的数据类型时,你可以使用下面的方法:

int[] arr = {7, 10, 4, 3, 20, 15};
int[] reverseArr = IntStream.rangeClosed(1, arr.length).map(i -> arr[arr.length-i]).toArray();

其他回答

你可以用这个:

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

Collections.reverseOrder()返回一个使用逆自然顺序的比较器。你可以使用Collections.reverseOrder(myComparator)来获得你自己的比较器的反向版本。

这里有很多乱七八糟的东西——人们建议非原始值的解决方案,尝试从基础上实现一些排序算法,给出涉及额外库的解决方案,炫耀一些俗套的解决方案等等。最初问题的答案是50/50。对于那些只想复制/粘贴的人:

// our initial int[] array containing primitives
int[] arrOfPrimitives = new int[]{1,2,3,4,5,6};

// we have to convert it into array of Objects, using java's boxing
Integer[] arrOfObjects = new Integer[arrOfPrimitives.length];
for (int i = 0; i < arrOfPrimitives.length; i++) 
    arrOfObjects[i] = new Integer(arrOfPrimitives[i]);

// now when we have an array of Objects we can use that nice built-in method
Arrays.sort(arrOfObjects, Collections.reverseOrder());

arrOfObjects现在是{6,5,4,3,2,1}。如果你有一个不是整数的数组——使用相应的对象而不是整数。

对于列表

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

对于数组

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

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

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

FWIW列表

Lists.reverse(a);

任何及所有收集

Collections.reverse(a);

这是我如何排序一个基本类型int数组。

int[] intArr = new int[] {9,4,1,7};
Arrays.sort(nums);
Collections.reverse(Arrays.asList(nums));

结果:

[1, 4, 7, 9]