对List根据某两个字段进行分组排序,排序字段·的类型为Date,即java代码实现ROW_NUMBER ( ) over ( PARTITION BY)语句
public <T> List<T> groupByOrder(List<T> originalList, String groupName, String orderName) throws IllegalAccessException {
List<T> result = new ArrayList<>();
if (ValidateUtil.validateNotEmpty(originalList)) {
Class classType = originalList.get(0).getClass();
Field groupField = ReflectionUtils.findField(classType, groupName);
ReflectionUtils.makeAccessible(groupField);
Map<String, List<T>> mapList = new HashMap<>();
for (T dto : originalList) {
String fieldValue = String.valueOf(groupField.get(dto));
// 先进行分组
if (mapList.containsKey(fieldValue)) {
mapList.get(fieldValue).add(dto);
}
else {
mapList.put(fieldValue, Lists.newArrayList(dto));
}
}
for (Map.Entry<String, List<T>> entry : mapList.entrySet()) { // 再进行排序
List<T> tempList = entry.getValue();
Field orderField = ReflectionUtils.findField(classType, orderName);
ReflectionUtils.makeAccessible(orderField);
Date tempDate = (Date) orderField.get(tempList.get(0));
T lastDto = tempList.get(0);
for (T dto : tempList) {
Date orderValue = (Date) orderField.get(dto);
if (orderValue.after(tempDate)) {
tempDate = orderValue;
lastDto = dto;
}
}
result.add(lastDto);
}
}
return result;
}