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

当前回答

如果列表中包含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了解更多详细信息。

其他回答

如果你必须根据对象在数组列表中的id来排序,那么使用java8流。

 List<Person> personList = new ArrayList<>();

    List<Person> personListSorted =
                personList.stream()
                  .sorted(Comparator.comparing(Person::getPersonId))
                  .collect(Collectors.toList());

在JAVA 8中,现在变得简单多了。

List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");
List<String> alphaNumbersUpperCase = alphaNumbers.stream()
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());
System.out.println(alphaNumbersUpperCase); // [FOUR, ONE, THREE, TWO]

——反过来用这个

.sorted(Comparator.reverseOrder())

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

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

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

降:

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;
    }
});
  yearList = arrayListOf()
    for (year in 1950 until 2021) {
        yearList.add(year)
    }

   yearList.reverse()
    val list: ArrayList<String> = arrayListOf()

    for (year in yearList) {
        list.add(year.toString())
    }