private static void ListSort(List<TaskVO> list) {
Collections.sort(list, new Comparator<TaskVO>() {
@Override
public int compare(TaskVO o1, TaskVO o2) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date r = format.parse("2013-02-25 10:20");
//r.getDate();
//string类型先转date 转过后获取 .getTime()
if (o1.getCreateDate().getTime() > o2.getCreateDate().getTime()) {
return -1; //降序 否则 升序
} else if (o1.getCreateDate().getTime() < o2.getCreateDate().getTime()) {
return 1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
}
--------------------------工具类
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @param targetList 目标排序List
* @param sortField 排序字段
* @param sortMode 排序方式
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> void sort(List<T> targetList, final String sortField, final String sortMode) {
Collections.sort(targetList, new Comparator() {
public int compare(Object obj1, Object obj2) {
int retVal = 0;
try {
Method method1 = ((T)obj1).getClass().getMethod(sortField, null);
Method method2 = ((T)obj2).getClass().getMethod(sortField, null);
if (sortMode != null && "desc".equals(sortMode)) {
retVal = method2.invoke(((T) obj2), null).toString().compareTo(method1.invoke(((T) obj1), null).toString()); // 倒序
} else {
retVal = method1.invoke(((T) obj1), null).toString().compareTo(method2.invoke(((T) obj2), null).toString()); // 正序
}
} catch (Exception e) {
throw new RuntimeException();
}
return retVal;
}
});
}