我在java中有一个双精度的列表,我想按降序排序数组列表。

输入数组列表如下:

List<Double> testList = new ArrayList();

testList.add(0.5);
testList.add(0.2);
testList.add(0.9);
testList.add(0.1);
testList.add(0.1);
testList.add(0.1);
testList.add(0.54);
testList.add(0.71);
testList.add(0.71);
testList.add(0.71);
testList.add(0.92);
testList.add(0.12);
testList.add(0.65);
testList.add(0.34);
testList.add(0.62);

输出应该是这样的

0.92
0.9
0.71
0.71
0.71
0.65
0.62
0.54
0.5
0.34
0.2
0.12
0.1
0.1
0.1

当前回答

使用java.util.Collections类的util方法,即

Collections.sort(list)

事实上,如果你想排序自定义对象你可以使用

Collections.sort(List<T> list, Comparator<? super T> c) 

参见集合API

其他回答

集合。sort允许您传递一个定义排序逻辑的Comparator实例。因此,我们可以简单地传递Collections.reverseOrder()来排序,而不是按自然顺序对列表进行排序,然后反转它:

// import java.util.Collections;
Collections.sort(testList, Collections.reverseOrder());

正如@Marco13所提到的,除了更习惯(可能更有效),使用倒序比较器可以确保排序是稳定的(这意味着当元素的顺序根据比较器相等时,它们的顺序不会改变,而倒序将改变顺序)

Collections.sort(testList);
Collections.reverse(testList);

这是你想要的。记住导入集合!

这里是集合的文档。

对于您的示例,这将在Java 8中发挥作用

List<Double> testList = new ArrayList();
testList.sort(Comparator.naturalOrder());

但是如果你想要排序对象的一些字段,你可以很容易地通过:

testList.sort(Comparator.comparing(ClassName::getFieldName));

or

 testList.sort(Comparator.comparing(ClassName::getFieldName).reversed());

or

 testList.stream().sorted(Comparator.comparing(ClassName::getFieldName).reversed()).collect(Collectors.toList());

来源:https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

降:

Collections.sort(mArrayList, new Comparator<CustomData>() {
    @Override
    public int compare(CustomData lhs, CustomData rhs) {
        // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
        return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;
    }
});

使用lambdas (Java8),并将其分解到最基本的语法(JVM将在这种情况下推断大量的语法),你会得到:

Collections.sort(testList, (a, b) -> b.compareTo(a));

更详细的版本:

// Implement a reverse-order Comparator by lambda function
Comparator<Double> comp = (Double a, Double b) -> {
    return b.compareTo(a);
};

Collections.sort(testList, comp);

使用lambda是可能的,因为Comparator接口只有一个方法要实现,因此VM可以推断正在实现哪个方法。由于参数的类型可以推断,所以不需要声明(即(a, b)而不是(Double a, Double b)。并且由于lambda体只有一行,并且该方法被期望返回一个值,因此返回值是推断出来的,不需要花括号。