下面的代码是根据学生年龄排序学生list 的一个例子:
import java.util.ArrayList;
import java.util.List;
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Perosn [name=" + name + ", age=" + age + "]";
}
}
public class App {
public static void main(String[] args) {
Liststudents = new ArrayList<>();
students.add(new Student("abc", 12));
students.add(new Student("bcd", 20));
students.add(new Student("cde", 17));
students.add(new Student("def", 25));
students.add(new Student("efg", 15));
students.sort((x, y) -> Integer.compare(x.getAge(), y.getAge()));
for (Student stu : students) {
System.out.println(stu);
}
}
}
运行结果: