方法1
要比较的对象实现 Comparable,实现 CompareTo 方法
public class Student implements Comparable<Student> {
private int id;
private String name;
private int age;
public Student() {
}
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student student) {
// 升序排
//return this.getAge() - student.getAge();
// 降序排
return -this.getAge() + student.getAge();
}
}
测试类
public class DemoComparable {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student(1, "马", 18));
list.add(new Student(2, "驴", 16));
list.add(new Student(3, "猪", 17));
Collections.sort(list);
System.out.println(list);
}
}
方法2
重写 Comparator<> 接口 compare 方法
public class DemoComparable {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student(1, "马", 18));
list.add(new Student(2, "驴", 16));
list.add(new Student(3, "猪", 17));
Collections.sort(list, new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
// 升序排
// return o1.getAge() - o2.getAge();
// 降序排
return -o1.getAge() + o2.getAge();
}
});
System.out.println(list);
}
}