我在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

当前回答

在Java8中,List接口上有一个默认的排序方法,如果您提供了Comparator,该方法将允许您对集合进行排序。你可以很容易地将问题中的例子排序如下:

testList.sort((a, b) -> Double.compare(b, a));

注意:lambda中的参数在传递给Double.compare时交换,以确保排序是降序的

其他回答

你可以这样用

ArrayList<Group> groupList = new ArrayList<>();
Collections.sort(groupList, Collections.reverseOrder());
Collections.reverse(groupList);

|*|

import java.util.Collections;

|=>排序Asc顺序:

Collections.sort(NamAryVar);

|=>

Collections.sort(NamAryVar, Collections.reverseOrder());

|*|颠倒列表顺序:

Collections.reverse(NamAryVar);

排序List的另一种方法是使用Collections框架;

在这种情况下使用SortedSet(列表中的bean应该实现Comparable,所以Double是可以的):

List<Double> testList;
...
SortedSet<Double> sortedSet= new TreeSet<Double>();
for(Double number: testList) {
   sortedSet.add(number);
}
orderedList=new ArrayList(sortedSet);

一般来说,要按列表中bean的属性排序,将列表中的所有元素放在SortedMap中,使用该属性作为键,然后从SortedMap中获取values()(该属性应该实现Comparable):

List<Bean> testList;
...
SortedMap<AttributeType,Bean> sortedMap= new TreeMap<AttributeType, Bean>();
for(Bean bean : testList) {
   sortedMap.put(bean.getAttribute(),bean);
}
orderedList=new ArrayList(sortedMap.values());

如果列表中包含Comparable元素,可以使用Collections.sort(list)对列表进行排序。否则我建议你像这样实现接口:

public class Circle implements Comparable<Circle> {}

当然,提供你自己的compareTo方法的实现,如下所示:

@Override
    public int compareTo(Circle another) {
        if (this.getD()<another.getD()){
            return -1;
        }else{
            return 1;
        }
    }

然后你可以再次使用collection .sort(list),因为现在list包含Comparable类型的对象,可以排序。顺序取决于compareTo方法。查看https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html了解更多详细信息。

对于您的示例,这将在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