有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?

还是说我必须停止懒惰,自己做这件事:[


当前回答

对于按降序排序的2D数组,只需翻转参数的位置

int[][] array= {
    {1, 5},
    {13, 1},
    {12, 100},
    {12, 85} 
};
Arrays.sort(array, (a, b) -> Integer.compare(a[1], b[1])); // for ascending order
Arrays.sort(array, (b, a) -> Integer.compare(a[1], b[1])); // for descending order

降序输出

12, 100
12, 85
1, 5
13, 1

其他回答

你可以用这个:

    Arrays.sort(data, Collections.reverseOrder());

Collections.reverseOrder()返回一个使用逆自然顺序的比较器。你可以使用Collections.reverseOrder(myComparator)来获得你自己的比较器的反向版本。

对于按降序排序的2D数组,只需翻转参数的位置

int[][] array= {
    {1, 5},
    {13, 1},
    {12, 100},
    {12, 85} 
};
Arrays.sort(array, (a, b) -> Integer.compare(a[1], b[1])); // for ascending order
Arrays.sort(array, (b, a) -> Integer.compare(a[1], b[1])); // for descending order

降序输出

12, 100
12, 85
1, 5
13, 1

另一种选择可能是(对于数字!!)

将数组乘以-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());