java List根据时间排序

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("张三", "2009-01-01 20:20:20")); 
list.add(new Man("李四", "2001-01-01 21:10:20")); 
list.add(new Man("王五", "2005-05-01 02:20:20")); 
list.add(new Man("1B", "2003-01-01 10:22:20")); 
list.add(new Man("2BBB", "2003-02-01 22:25:20")); 
list.add(new Man("3BBB", "2004-01-01 23:22:20")); 
list.add(new Man("4BBB", "2003-05-01 01:22:20")); 
list.add(new Man("5BBB", "2007-01-01 02:25:20")); 
list.add(new Man("6BBB", "2008-01-01 08:28:20")); 
list.add(new Man("7BBB", "2000-01-01 05:24:20")); 
list.add(new Man("8BBB", "2001-04-01 07:26:20")); 
list.add(new Man("9BBB", "2002-01-01 09:27:20")); 
list.add(new Man("10BBB", "2003-07-01 11:29:20")); 
list.add(new Man("11BBB", "2003-06-01 12:21:20")); 
list.add(new Man("12BBB", "2003-11-01 19:22:20")); 
list.add(new Man("13BBB", "2005-06-01 15:25:20")); 
list.add(new Man("14BBB", "2008-08-01 18:22:20")); 
System.out.println("排序前:" + list); 
Collections.sort(list, new Comparator<Man>() { 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
private Date getBirthday(Man m) { 
if (m == null || m.getBirthday() == null) 
return null; 
try { 
return sdf.parse(m.getBirthday().substring(11)); 
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);
}
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值