java list 排序 Collections.sort(list,comparator)的写法完整代码
public class SsvlistInfoCompare implements Comparator<Date> {
/**
*
*/
@Override
public int compare( Date a, Date b ) {
//如果a 大于b 返回 整数 1 、相等返回 0 、小于返回 -1
//按升序排列 如果要设置成降序写成b.compareTo(a);
int flag = a.compareTo( b );
System.out.println(flag);
return flag;
}
public static void main (String[] strs){
List<Date> list =new ArrayList<Date>();
Date info1 = StringToDate( "2012-12-10 00:00:00" );
Date info2 = StringToDate( "2012-12-07 00:00:00" );
Date info3 = StringToDate( "2012-12-08 00:00:00" );
Date info4 = StringToDate( "2012-12-10 00:00:00" );
list.add( info1 );
list.add( info2 );
list.add( info3 );
list.add( info4 );
SsvlistInfoCompare s= new SsvlistInfoCompare();
//实现顺序或者倒序排列
Collections.sort( list, s );
for ( int i = 0; i < list.size(); i++ ) {
Date info = list.get( i );
//System.out.println(info.getPhotoDate());
System.out.println(dateToString( info));
}
}
/**
* 格式字符串转换为字符串 yyyy-MM-dd HH:mm:ss
*
* @param strDate
* @return
*/
public static String dateToString( Date date ) {
if ( date == null ) {
return "";
}
else {
SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
String dateStr = formatter.format( date );
return dateStr;
}
}
/**
* 字符串转换为时间 yyyy-MM-dd HH:mm:ss
*
* @param strDate
* @return
*/
public static Date StringToDate( String datestr ) {
SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
Date dateStr = null;
try {
dateStr = formatter.parse( datestr );
}
catch ( ParseException e ) {
e.printStackTrace();
}
return dateStr;
}
}