有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
我知道这是一个相当老的线程,但这里是一个更新版本的整数和Java 8:
Arrays.sort(array, (o1, o2) -> o2 - o1);
注意,对于正常的升序(或Comparator.comparingInt()),它是“o1 - o2”。
这也适用于任何其他类型的对象。说:
Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());
其他回答
这是我如何排序一个基本类型int数组。
int[] intArr = new int[] {9,4,1,7};
Arrays.sort(nums);
Collections.reverse(Arrays.asList(nums));
结果:
[1, 4, 7, 9]
我知道这里有很多答案,但仍然认为,没有人尝试使用核心java。 使用集合api,你最终会浪费这么多的内存和残差。
这是一个纯核心概念的尝试,是的,如果你更关心内存占用,这可能是更好的方法。
int[] elements = new int [] {10,999,999,-58,548,145,255,889,1,1,4,5555,0,-1,-52};
//int[] elements = null;
if(elements != null && elements.length >1)
{
int max = 0, index = 0;
for(int i =0;i<elements.length;i++)//find out what is Max
{
if(elements[i] > max)
{
max = elements[i];
index = i;
}
}
elements[index] = elements[0];//Swap the places
elements[0] = max;
for(int i =0;i < elements.length;i++)//loop over element
{
for(int j = i+1;j < elements.length;j++)//loop to compare the elements
{
if(elements[j] > elements[i])
{
max = elements[j];
elements[j] = elements[i];
elements[i] = max;
}
}
}
}//i ended up using three loops and 2 extra variables
System.out.println(Arrays.toString(elements));//if null it will print null
// still love to learn more, please advise if we can do it better.
我也喜欢向你学习!
这里有很多乱七八糟的东西——人们建议非原始值的解决方案,尝试从基础上实现一些排序算法,给出涉及额外库的解决方案,炫耀一些俗套的解决方案等等。最初问题的答案是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}。如果你有一个不是整数的数组——使用相应的对象而不是整数。
Java 8:
Arrays.sort(list, comparator.reversed());
更新: Reversed()反转指定的比较器。通常比较器的顺序是升序的,所以这将顺序改为降序。
不能直接使用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]