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