使用Collections.sort
实体类
@Data
public class Student {
private String name;
private Integer age;
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
}
方法一 直接调用
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("张三",20));
students.add(new Student("李四",16));
students.add(new Student("王五",18));
students.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if (o1.getAge()> o2.getAge()) {
return 1;
}else if (o1.getAge() < o2.getAge()) {
return -1;
}else {
return 0;
}
}
});
students.forEach(System.out::println);
}
方法二 在实体类重写compare方法,直接调用sort方法即可
```
@Data
public class Student implements Comparable<Student>{
private String name;
private Integer age;
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o)
{
if (this.getAge() > o.getAge()){
return 1;
} else if (this.getAge() < o.getAge()) {
return -1;
}else {
return 0;
}
}
}
```