集合排序按照时间以及工具类

private static void ListSort(List<Work_log> list) {
Collections.sort(list, new Comparator<Work_log>() {
@Override
public int compare(Work_log o1, Work_log o2) {
try {
// if (o1.getStart_date().getTime() > o2.getStart_date().getTime()) {
// return -1; //降序
// } else
// if (o1.getStart_date().getTime() < o2.getStart_date().getTime()) {
// return 1;
// } else {
// return 0;
// }
if(o1.getStart_date().after(o2.getStart_date())){
return 1;//升序
}
return -1;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});

}

 

 

 

 

 

 

--------------------------工具类

//sort(randomList, "getType", "desc");//排序题


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;
}
});
}

 

List<Map<String,Object>> list=new ArrayList<>();
Map<String,Object> map1=new HashMap<>();
map1.put("a", 1);
map1.put("create", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-09-10 23:59:59"));
list.add(map1);
Map<String,Object> map2=new HashMap<>();
map2.put("a", 2);
map2.put("create", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-09-30 23:59:59"));
list.add(map2);
Map<String,Object> map3=new HashMap<>();
map3.put("a", 3);
map3.put("create", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2020-09-19 23:59:59"));
list.add(map3);

list.sort((a,b)->{
Date d = (Date) a.get("create");
Date e = (Date) b.get("create");
if(d.getTime()>e.getTime()){
return 1;
}else{
return -1;
}

});
for (Map<String, Object> item : list) {
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item.get("create")));
}

posted @ 2019-06-21 14:42  小农_码  阅读(495)  评论(0编辑  收藏  举报