对封装好的数据进行排序(根据其中某一数据) – Java

public static void main(String[] args) throws ParseException {

        String []names = {"张三","李四","王五"};
        char []sexs = {'男','女','女'};
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date []dates = {sdf.parse("1991-09-08"),sdf.parse("1996-05-08"),sdf.parse("1989-06-08")};
        List<Per> list = new ArrayList<>();
        //添加数据
        for (int i = 0; i < names.length; i++) {
            list.add(new Per(names[i],sexs[i],dates[i]));
        }

        System.out.println("---------------原数据------------------");

        for (Per p : list) {
            System.out.println(p.toString());
        }

        System.out.println("------------排序后的数据----------------");

        list = maopao(list);
        for (Per p : list) {
            System.out.println(p.toString());
        }

        System.out.println("---------------------------------------");
    }

    /**
     * 对封装好的Per中的日期进行冒泡排序
     * @param list  排序前数据
     * @return  排序后数据
     */
    public static List<Per> maopao(List<Per> list){
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = 0; j < list.size() - 1 - i; j++) {
                if(list.get(j).getDate().after(list.get(j + 1).getDate())){
                    Per temp = list.get(j + 1);
                    list.set(j + 1, list.get(j));
                    list.set(j, temp);
                }
            }
        }
        return list;
    }


    static class Per{
        private String name;
        private Character sex;
        private Date date;

        public Per() {
        }

        public Per(String name, Character sex, Date date) {
            this.name = name;
            this.sex = sex;
            this.date = date;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Character getSex() {
            return sex;
        }

        public void setSex(Character sex) {
            this.sex = sex;
        }

        public Date getDate() {
            return date;
        }

        public void setDate(Date date) {
            this.date = date;
        }

        @Override
        public String toString() {
            return "per{" +
                    "name='" + name + '\'' +
                    ", sex=" + sex +
                    ", date=" + date +
                    '}';
        }
    }

发表评论