对List集合中每个对象元素按时间顺序排序

x33g5p2x  于2022-05-31 转载在 其他  
字(4.3k)|赞(0)|评价(0)|浏览(406)

需求: 需要对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.*;

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;
            }
        });
    }
}

List集合, 时间正序排列、倒序排序

public class Test {
        public static void main(String[] args) {
            //MySQL识别的日期格式
            String str01 = "2021-06-26T12:11:52.000+0000";
            String str02 = "2021-06-25T12:08:41.000+0000";
            String str03 = "2021-06-27T12:18:22.000+0000";
            Student student01 = new Student(1, "张三", dealDateFormat(str01));
            Student student02 = new Student(2, "李四", dealDateFormat(str02));
            Student student03 = new Student(3, "王五", dealDateFormat(str03));
            List<Student> arrayList = new ArrayList<>();
            Collections.addAll(arrayList, student01, student02, student03);
            //TODO:正序排列[最小的时间在前]
            // 输出: [{"date":"2021-06-25 12:08:41","name":"李四","id":2},
            // {"date":"2021-06-26 12:11:52","name":"张三","id":1},
            // {"date":"2021-06-27 12:18:22","name":"王五","id":3}]

            Collections.sort(arrayList, Comparator.comparing(Student::getDate));
            System.out.println(JSON.toJSON(arrayList));
            
            //TODO:倒序排序[最大的在前]
            //输出: [{"date":"2021-06-27 12:18:22","name":"王五","id":3},
            // {"date":"2021-06-26 12:11:52","name":"张三","id":1},
            // {"date":"2021-06-25 12:08:41","name":"李四","id":2}]        
            Collections.sort(arrayList, new CalendarComparator());
            System.out.println(JSON.toJSON(arrayList));
        }

        // 时间倒序排序    
        private static class CalendarComparator implements Comparator {
            public int compare(Object object1, Object object2) {
                //实现接口中的方法            
                Student p1 = (Student) object1; // 强制转换           
                Student p2 = (Student) object2;
                return p2.getDate().compareTo(p1.getDate());
            }
        }
    }
static String dealDateFormat(String oldDate) {
        Date date1 = null;
        DateFormat df2 = null;
        try {
            DateFormat df = new SimpleDateFormat(ExchangeConstants.FORMAT_T);
            Date date = df.parse(oldDate);
            SimpleDateFormat df1 = new SimpleDateFormat(ExchangeConstants.FORMAT_Z, Locale.UK);
            date1 = df1.parse(date.toString());
            df2 = new SimpleDateFormat(ExchangeConstants.FORMAT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return df2.format(date1);
    }

相关文章