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

当前回答

你可以这样做:

List<String> yourList = new ArrayList<String>();
Collections.sort(yourList, Collections.reverseOrder());

集合有一个默认的比较器可以帮助你。

另外,如果你想使用一些Java 8的新特性,你可以这样做:

List<String> yourList = new ArrayList<String>();
yourList = yourList.stream().sorted(Collections.reverseOrder()).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())

降:

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;
    }
});

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

使用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体只有一行,并且该方法被期望返回一个值,因此返回值是推断出来的,不需要花括号。

排序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());