【工具类】排序工具类
List、Map 按日期倒序排序
import com.alibaba.fastjson.JSONObject;
import java.text.SimpleDateFormat;
import java.util.*;
public class SortUtil {
/**
* list按日期排序 倒序
*
* @param list
* @param dateKey 排序的字段名
* @param dateFormat 排序的日期格式
*/
public static void ListSort(List<JSONObject> list, String dateKey, String dateFormat) {
Collections.sort(list, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject n1, JSONObject n2) {
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
try {
Date dt1 = format.parse(n1.getString(dateKey));
Date dt2 = format.parse(n2.getString(dateKey));
if (dt1.getTime() > dt2.getTime()) {
return -1;
} else if (dt1.getTime() < dt2.getTime()) {
return 1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
});
}
/**
* map按日期key排序 倒序
*
* @param map
* @param dateFormat 排序的日期格式
*/
public static <E> Map<String, E> MapSort(Map<String, E> map, String dateFormat) {
Map<String, E> sortMap = new TreeMap<>(
new MapKeyComparator(dateFormat));
sortMap.putAll(map);
return sortMap;
}
static class MapKeyComparator implements Comparator<String>{
private String dateFormat;
public MapKeyComparator(String dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public int compare(String s1, String s2) {
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
try {
Date dt1 = format.parse(s1);
Date dt2 = format.parse(s2);
if (dt1.getTime() > dt2.getTime()) {
return -1;
} else if (dt1.getTime() < dt2.getTime()) {
return 1;
} else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
}
使用:
public void listSort() {
List<JSONObject> dateGroupList = new ArrayList<>();
SortUtil.ListSort(dateGroupList, "date", "yyyy-MM-dd");
}
public void mapSort() {
List<JSONObject> countList = mapper.selectList();
// 按月分组
Map<String, List<JSONObject>> collect = countList.stream()
.collect(Collectors.groupingBy(item -> item.getString("date").substring(0, 7)));
collect = SortUtil.MapSort(collect, "yyyy-MM");
}