两种方法
- 实体类实现comparable接口,重写compareTo方法
- 新建比较器类实现comparator接口,重写compare方法
comparable 步骤
- 实体类实现comparable接口,重写compareTo方法
- 调用Collections.sort(list)方法。
@Data
public class Student implements Comparable<Student>{
private String name;
private int age;
private Date birthDay;
public Student(String name, int age, String birthDay) {
this.name = name;
this.age = age;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
this.birthDay = dateFormat.parse(birthDay);
} catch (ParseException e) {
e.printStackTrace();
};
}
//按名字降序 按生日升序
@Override
public int compareTo(Student student) {
int result=0;
result=-this.name.compareTo(student.name);
if(result==0){
result=this.birthDay.compareTo(student.birthDay);
}
return result;
}
}
package io;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class App {
public static void main(String[] args) {
List<Student> list=new ArrayList<Student>();
list.add(new Student("张三", 20, "1987-10-5"));
list.add(new Student("王五", 22, "1986-10-5"));
list.add(new Student("赵六", 25, "1988-10-5"));
list.add(new Student("王七", 19, "1980-10-5"));
Collections.sort(list);
}
}
新建比较器类,实现comparator接口
重写compare方法
Collections.sort(list, new BirthdayComp()); 将业务类对象作为参数传入Collections.sort方法中
package io;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Student {
private String name;
private int age;
private Date birthDay;
public Student(String name, int age, String birthDay) {
this.name = name;
this.age = age;
DateFormat ds=new SimpleDateFormat("yyyy-MM-dd");
try {
this.birthDay = ds.parse(birthDay);
} catch (ParseException e) {
e.printStackTrace();
};
}
}
import java.util.Comparator;
public class BirthdayComp implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.getBirthDay().compareTo(o2.getBirthDay());
}
}
package io;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class App {
public static void main(String[] args) {
List<Student> list=new ArrayList<Student>();
list.add(new Student("张三", 20, "1987-10-5"));
list.add(new Student("王五", 22, "1986-10-5"));
list.add(new Student("赵六", 25, "1988-10-5"));
list.add(new Student("王七", 19, "1980-10-5"));
Collections.sort(list, new BirthdayComp());
for(Student s:list){
System.out.println(s);
}
}
}