java排序例子

package csdn;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class Test {

    public static class Man {

        private String birthday;
        private String name;

        public Man() {
        }

        public Man(String name, String birthday) {
            this.name = name;
            this.birthday = birthday;
        }

        @Override
        public String toString() {
            return name + "  " + birthday;
        }

        public String getName() {
            return name;
        }

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

        public String getBirthday() {
            return birthday;
        }

        public void setBirthday(String birthday) {
            this.birthday = birthday;
        }
    }

    public static void main(String[] args) {
        List<Man> list = new ArrayList<Man>();
        list.add(new Man("张三", "2000-01-01 20:20:20"));
        list.add(new Man("李四", "2001-01-01 20:20:20"));
        list.add(new Man("王五", "2005-05-01 20:20:20"));
        list.add(new Man("BBB", "2003-01-01 20:20:20"));

        System.out.println("排序前:" + list);
        Collections.sort(list, new Comparator<Man>() {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

            private Date getBirthday(Man m) {
                if (m == null || m.getBirthday() == null)
                    return null;
                try {
                    return sdf.parse(m.getBirthday());
                } catch (ParseException e) {
                    return null;
                }
            }

            public int compare(Man o1, Man o2) {
                Date d1 = getBirthday(o1);
                Date d2 = getBirthday(o2);
                if (d1 == null && d2 == null)
                    return 0;

                if (d1 == null)
                    return -1;
                if (d2 == null)
                    return 1;
                return d1.compareTo(d2);
            }

        });
        System.out.println("排序后:" + list);
    }

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值