需求说明
例如一个ArrayList里面存有students,要按照student的某个属性(例如序号或者年龄)排序。
Student示例:
public class Student implements Serializable {
private Integer no; // 学号
private int age; // 年龄
private String name; // 姓名
public Student(Integer no, String name, int age) {
this.no = no;
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
}
有如下ArrayList:
List<Student> students = new ArrayList<>(); students.add(new Student(1, "张三", 18)); students.add(new Student(2, "李四", 20)); students.add(new Student(3, "王五", 16));
实现排序
可以使用Collections.sort方法:
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student student1, Student student2) {
return student1.getAge() - student2.getAge();
// return student1.getNo().compareTo(student2.getNo()); // 如果按照学号排序,这样做
}
});
// 使用lamda 这样做:
Collections.sort(students, Comparator.comparing(Student::getNo));
也可以直接使用students的sort方法或者stream方法
// 按照年龄排序 students.sort(Comparator.comparing(Student::getAge)); // 按照年龄的倒序排序: students.sort((t1, t2) -> t2.getAge() - t1.getAge()); // 按照学号排序 students.sort(Comparator.comparing(Student::getNo)); // 按照学号倒序: students.sort((t1, t2) -> t2.getNo().compareTo(t1.getNo())); // 使用stream排序并打印 students.stream().sorted(Comparator.comparing(Student::getAge)).forEach(System.out::println);
文章评论