需求: 需要对List中的每个student对象按照birthday顺序排序,时间由小到大排列。
1. 刚开始用的是冒泡排序,出现数据覆盖的情况
for (int i = 0; i < list.size() - 1; i++) {
for (int j = 0; j < list.size() - 1 - i; j++) {
long time = list.get(j).getCreateAt().getTime();
long time1 = list.get(j + 1).getCreateAt().getTime();
if (time >time1) {
t
Object temp = list.get(j+1);
BeanUtils.copyProperties(list.get(j), list.get(j+1));
BeanUtils.copyProperties(temp, list.get(j));
}
}
2. 之后想到了Comparator比较器
public static <T> void sort(List<T> list,Comparator<? super T> ),
这个里面就涉及到了Comparator 这个接口,位于位于java.util包下,排序是comparator能实现的功能之一,通俗地讲需要比较两个对象 谁排在前谁排在后,那么比较的方法就是:
- public int compare(String o1, String o2):比较其两个参数的顺序
两个对象比较的结果有三种:大于,等于,小于。
如果要按照升序排序, 则o1 小于o2,返回(负数),相等返回0,01大于02返回(正数)
如果要按照降序排序 则o1 小于o2,返回(正数),相等返回0,01大于02返回(负数)
操作如下
package com.hbsi.test;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author lbq
* @date 2020 10 15:07
*/
public class ListSort {
static class Student {
private String userName;
private String birthday;
public Student() {
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student{" +
"userName='" + userName + '\'' +
", birthday='" + birthday + '\'' +
'}';
}
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
List<Student> list = new ArrayList<Student>();
s1.setUserName("aa");
s1.setBirthday("1997-01-08");
s2.setUserName("bb");
s2.setBirthday("1990-11-08");
s3.setUserName("cc");
s3.setBirthday("1957-05-08");
list.add(s1);
list.add(s2);
list.add(s3);
System.out.println("排序前:");
for (Student o : list) {
System.out.println(o);
}
listSort(list);
System.out.println("排序后:");
for (Student o : list) {
System.out.println(o);
}
}
private static void listSort(List<Student> list) {
Collections.sort(list, new Comparator<Student>() {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
public int compare(Student o1, Student o2) {
try {
Date dt1 = sf.parse(o1.getBirthday());
Date dt2 = sf.parse(o2.getBirthday());
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
}
}