lambda表达式常用的list排序
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static java.util.Comparator.comparing;
public class LambdaTest {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.addAll(Arrays.asList(
new Person(12, 178, "张三2"),
new Person(12, 176, "李四"),
new Person(16, 180, "王五"))
);
System.out.println(personList);
//普通排序
personList.sort(new Comparator<Person>() {
public int compare(Person a1, Person a2) {
return a1.getAge().compareTo(a2.getAge());
}
});
//lambda排序1
personList.sort((Person a1, Person a2) -> a1.getAge().compareTo(a2.getAge()));
//lambda排序2
personList.sort((a1, a2) -> a1.getAge().compareTo(a2.getAge()));
//lambda排序3
personList.sort(comparing(Person::getAge)); //正序排序
personList.sort(comparing(Person::getAge).reversed()); //倒序排序
//如果年龄一样,按照身高排序1
personList.sort((a1, a2) -> {
if (a1.getAge() == a2.getAge()) {
return a1.getHeight() - a2.getHeight();
}else{
return a1.getAge() - a2.getAge();
}
});
//如果年龄一样,按照身高排序2
personList.sort(comparing(Person::getAge).thenComparing(Person::getHeight));
System.out.println(personList);
}
}
public class Person {
private Integer age;
private Integer height;
private String name;
public Person(Integer age, Integer height, String name) {
this.age = age;
this.height = height;
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", height=" + height +
", name='" + name + '\'' +
'}';
}
}