java的list集合如何根据对象中的某个字段排序
1个回答
展开全部
下面的代码是根据学生年龄排序学生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) {
List<Student> students = 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);
}
}
}
运行结果:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询