package com.example.study.util;
import cn.hutool.core.collection.CollUtil;
import com.itextpdf.styledxmlparser.jsoup.internal.StringUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.Collator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* @date 2024-04-26
*/
public class SortUtil {
/**
* 倒序
*/
private static final String DESC = "desc";
/**
* 对list进行排序
* @param list 需要排序的列表
* @param sort 需要进行排序的对象字段(需要含有相应的get方法)
* @param order asc 正序,desc 反序
* @param chinese 是否中文拼音排序
*/
public static <E> void sort(List<E> list, String sort, String order,boolean chinese) {
if(CollUtil.isEmpty(list)){
return;
}
if(StringUtil.isBlank(sort)){
return;
}
Collator instance = Collator.getInstance(Locale.CHINA);
//获取指定字段的get方法名
String methodName = "get" + sort.toUpperCase().substring(0, 1).toUpperCase() + sort.substring(1);
list.sort((a, b) -> {
int result = 0;
try {
//获取方法
Method m1 = a.getClass().getMethod(methodName, null);
Method m2 = b.getClass().getMethod(methodName, null);
Object obj1 = m1.invoke((E)a);
Object obj2 = m2.invoke((E)b);
//空值排后面
if(null == obj1 && null == obj2){
result = 0 ;
}else if(null == obj1){
result = 1 ;
}else if(null == obj2){
result = -1 ;
}else{
if(obj1 instanceof String) {
if(chinese) {
result = instance.compare(obj1,obj2);
}else{
result = ((String) obj1).compareTo((String) obj2);
}
}else if(obj1 instanceof Date) {
result = ((Date)obj1).compareTo((Date)obj2);
}else if(obj1 instanceof Integer) {
result = ((Integer)obj1).compareTo((Integer)obj2);
}else if(obj1 instanceof BigDecimal) {
result = ((BigDecimal)obj1).compareTo((BigDecimal)obj2);
}
if (DESC.equals(order)){
// 倒序
result = - result;
}
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ne) {
ne.printStackTrace();
}
return result;
});
}
}