有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
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;
}
其他回答
您可以使用Comparator.reverseOrder()来使用流操作(Collections.stream())。
例如,假设你有这样一个集合:
List<String> items = new ArrayList<>();
items.add("item01");
items.add("item02");
items.add("item03");
items.add("item04");
items.add("item04");
你可以使用sorted()方法以“自然”的顺序打印项目(或者不用它,得到相同的结果):
items.stream()
.sorted()
.forEach(item -> System.out.println(item));
或者要按降序(倒序)打印它们,你可以使用带Comparator的sorted方法并颠倒顺序:
items.stream()
.sorted(Comparator.reverseOrder())
.forEach(item -> System.out.println(item));
注意,这要求集合已经实现Comparable(如Integer、String等)。
这里有很多乱七八糟的东西——人们建议非原始值的解决方案,尝试从基础上实现一些排序算法,给出涉及额外库的解决方案,炫耀一些俗套的解决方案等等。最初问题的答案是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}。如果你有一个不是整数的数组——使用相应的对象而不是整数。
你可以使用这个对所有类型的对象进行排序
sort(T[] a, Comparator<? super T> c)
Arrays.sort(a, Collections.reverseOrder());
arrays .sort()不能直接用于按降序对基本数组进行排序。如果试图通过传递Collections.reverseOrder()定义的反向Comparator来调用Arrays.sort()方法,它将抛出错误
没有合适的sort方法(int[],comparator)
这将很好地工作与“对象数组”,如Integer Array,但将不适用于原始数组,如int Array。
按降序对原始数组排序的唯一方法是,首先按升序对数组排序,然后在适当的位置反转数组。这对于二维基元数组也是成立的。
首先,你需要使用以下命令对数组进行排序:
Collections.sort(myArray);
然后你需要使用以下命令将升序颠倒为降序:
Collections.reverse(myArray);
我知道这是一个相当老的线程,但这里是一个更新版本的整数和Java 8:
Arrays.sort(array, (o1, o2) -> o2 - o1);
注意,对于正常的升序(或Comparator.comparingInt()),它是“o1 - o2”。
这也适用于任何其他类型的对象。说:
Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());