有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
没有显式比较器:
Collections.sort(list, Collections.reverseOrder());
使用显式比较器:
Collections.sort(list, Collections.reverseOrder(new Comparator()));
其他回答
我不知道你的用例是什么,但是除了这里的其他答案之外,另一个(惰性)选项是仍然按照你指出的升序排序,但然后以反向顺序迭代。
另一种选择可能是(对于数字!!)
将数组乘以-1 排序 再乘以-1
从字面上说:
array = -Arrays.sort(-array)
另一种使用Comparator的方法
import java.util.Arrays;
import java.util.Comparator;
...
Integer[] aInt = {6,2,3,4,1,5,7,8,9,10};
Arrays.sort(aInt, Comparator.reverseOrder() );
我知道这是一个相当老的线程,但这里是一个更新版本的整数和Java 8:
Arrays.sort(array, (o1, o2) -> o2 - o1);
注意,对于正常的升序(或Comparator.comparingInt()),它是“o1 - o2”。
这也适用于任何其他类型的对象。说:
Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());
我有下面的工作解决方案
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;
}