方法1:
使用Collections.sort(list),要求list里面的对象可以做比较,则需要implements Comparable接口。
public class Student implements Comparable<Student>{
private Integer Id;
private Integer age;
private String name;
public Student(Integer id, Integer age, String name) {
Id = id;
this.age = age;
this.name = name;
}
public Integer getAge() {
return age;
}
@Override
public String toString() {
return "Student{" +
"Id=" + Id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
@Override
public int compareTo(Student o) {
return this.Id-o.Id;
}
}
方法2:
可以直接使用list.sort()方法,但需要自定义比较方法
list.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()-o2.getAge();
}
});
Main方法
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Student> list=new ArrayList<>();
list.add(new Student(1,20,"1111"));
list.add(new Student(3,13,"3333"));
list.add(new Student(4,30,"4444"));
list.add(new Student(2,25,"2222"));
Collections.sort(list);
System.out.println(list);
list.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()-o2.getAge();
}
});
System.out.println(list);
}
}