我在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
例如,我有一个类Person: String name, int age ==>构造函数new Person(name,age)
import java.util.Collections;
import java.util.ArrayList;
import java.util.Arrays;
public void main(String[] args){
Person ibrahima=new Person("Timera",40);
Person toto=new Person("Toto",35);
Person alex=new Person("Alex",50);
ArrayList<Person> myList=new ArrayList<Person>
Collections.sort(myList, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
// return p1.age+"".compareTo(p2.age+""); //sort by age
return p1.name.compareTo(p2.name); // if you want to short by name
}
});
System.out.println(myList.toString());
//[Person [name=Alex, age=50], Person [name=Timera, age=40], Person [name=Toto, age=35]]
Collections.reverse(myList);
System.out.println(myList.toString());
//[Person [name=Toto, age=35], Person [name=Timera, age=40], Person [name=Alex, age=50]]
}
对于您的示例,这将在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