调用Collections.sort()方法,比较两个Person对象(先按年龄比,年龄相同按姓名比),使用Lambda表达式作为参数传递。?
public class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//重写toString方法
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Person> list = Arrays.asList(new Person("小亮", 22),
new Person("李四", 23), new Person("小明", 20),
new Person("张三", 20));
//sort 方法传入的是一个比较器 Comparator<? super T> c
Collections.sort(list,(a, b) ->{
int num = Integer.compare(a.age, b.age);
int num2 = num==0?a.name.compareTo(b.name):num;
return num2; //有多行表达式时一定要写return
});
for (Person employee : employeeList) {
System.out.println(employee.toString());
}
}
}
运行结果:
|