有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
首先,你需要使用以下命令对数组进行排序:
Collections.sort(myArray);
然后你需要使用以下命令将升序颠倒为降序:
Collections.reverse(myArray);
其他回答
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;
}
你可以用这个:
Arrays.sort(data, Collections.reverseOrder());
Collections.reverseOrder()返回一个使用逆自然顺序的比较器。你可以使用Collections.reverseOrder(myComparator)来获得你自己的比较器的反向版本。
对于包含原语元素的数组,如果有org.apache.commons.lang(3)可供处置,则简单的反向数组(排序后)的方法是使用:
ArrayUtils.reverse(array);
不能直接使用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]
这里有很多乱七八糟的东西——人们建议非原始值的解决方案,尝试从基础上实现一些排序算法,给出涉及额外库的解决方案,炫耀一些俗套的解决方案等等。最初问题的答案是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}。如果你有一个不是整数的数组——使用相应的对象而不是整数。