import entity.Student;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* List 排序测试
* @author : ZhouMei
* @date Date : 2022年08月11日 15:03
* @Description: TODO
*/
public class ListTest {
public static void main(String[] args) {
List<Student> list = new ArrayList();
list.add(new Student(1, "张三", 23));
list.add(new Student(2, "李四", 18));
list.add(new Student(3, "王五", 22));
list.add(new Student(4, "赵六", 21));
Collections.sort(list);
System.out.println("使用Student类默认比较器排序后的结果:" + list);
Collections.sort(list, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
//按年龄倒序
return s2.getAge() - s1.getAge();
}
});
System.out.println("使用自定义比较器排序后的结果:" + list);
}
}
package entity;
import lombok.Data;
/**
* @author : ZhouMei
* @date Date : 2022年08月11日 10:20
* @Description: TODO
*/
@Data
public class Student implements Comparable {
private Integer id;
private String name;
private Integer age;
public int compareTo(Object o1) {
Student s1 = (Student) o1;
if(this.age > s1.age){
return 1;
}
if(this.age == s1.age){
return this.name.compareTo(s1.name);
}
return -1;
}
public Student(Integer id, String name, Integer age){
this.id = id;
this.name = name;
this.age = age;
}
}
使用Student类默认比较器排序后的结果:[Student(id=2, name=李四, age=18), Student(id=4, name=赵六, age=21), Student(id=3, name=王五, age=22), Student(id=1, name=张三, age=23)]
使用自定义比较器排序后的结果:[Student(id=1, name=张三, age=23), Student(id=3, name=王五, age=22), Student(id=4, name=赵六, age=21), Student(id=2, name=李四, age=18)]