有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
这是我如何排序一个基本类型int数组。
int[] intArr = new int[] {9,4,1,7};
Arrays.sort(nums);
Collections.reverse(Arrays.asList(nums));
结果:
[1, 4, 7, 9]
其他回答
Java 8:
Arrays.sort(list, comparator.reversed());
更新: Reversed()反转指定的比较器。通常比较器的顺序是升序的,所以这将顺序改为降序。
没有显式比较器:
Collections.sort(list, Collections.reverseOrder());
使用显式比较器:
Collections.sort(list, Collections.reverseOrder(new Comparator()));
当一个数组是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();
我有下面的工作解决方案
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;
}
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;
}