import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* 依照前端传过来的vo字段 获取字段类型 进行排序
* @author fuzhi
* @date 2019-01-15
*/
@Slf4j
public class SortUtil {
/**
* @param list 返回给前端的list
* @param orderBy 要排序字段
* @param direction 正序 asc 倒序 desc
* @return List
*/
public static List getSortedList(List list, String orderBy, String direction) {
if (StringUtils.isNotBlank(orderBy) && StringUtils.isNotBlank(direction)) {
List li = (List) list.stream().sorted((o1, o2) -> {
try {
Field field1 = o1.getClass().getDeclaredField(orderBy);
Field field2 = o2.getClass().getDeclaredField(orderBy);
/** 获取private属性*/
field1.setAccessible(true);
field2.setAccessible(true);
if(field1.getType().toString().endsWith("String")){
String a1 = (String) field1.get(o1);
String a2 = (String) field2.get(o2);
if ((null != a1) && (null != a2)) {
String a11 = new String(a1.getBytes("GB2312"),"ISO-8859-1");
String a22 = new String(a2.getBytes("GB2312"),"ISO-8859-1");
if ("asc".equals(direction)) {
return a11.compareTo(a22);
}
if ("desc".equals(direction)) {
return a22.compareTo(a11);
}
}else {
{
if ("asc".equals(direction)) { if (null == a1) {return -1;}return 1; }
if ("desc".equals(direction)) { if (null == a1) {return 1;}else { return -1; }}
}
}
}
if (field1.getType().toString().endsWith("BigDecimal")) {
BigDecimal a1 = ((BigDecimal) field1.get(o1));
BigDecimal a2 = (BigDecimal) field2.get(o2);
if ((null != a1) && (null != a2)) {
if ("asc".equals(direction)) {
return a1.compareTo(a2);
}
if ("desc".equals(direction)) {
return a2.compareTo(a1);
}
} else {
{
if ("asc".equals(direction)) { if (null == a1) {return -1;}return 1; }
if ("desc".equals(direction)) { if (null == a1) {return 1;}else { return -1; }}
}
}
}
if (field1.getType().toString().endsWith("Date")) {
Date a1 = ((Date) field1.get(o1));
Date a2 = (Date) field2.get(o2);
if ((null != a1) && (null != a2)) {
if ("asc".equals(direction)) {
return a1.compareTo(a2);
}
if ("desc".equals(direction)) {
return a2.compareTo(a1);
}
} else {
{
if ("asc".equals(direction)) {
if (null == a1) { return -1; }else { return 1; }}
if ("desc".equals(direction)) {
if (null == a1) {return 1;}else{ return -1; }}
}
}
}
if(field1.getType().toString().endsWith("Int")||field1.getType().toString().endsWith("Integer")){
Integer a1 = ((Integer) field1.get(o1));
Integer a2 = (Integer) field2.get(o2);
if ((null != a1) && (null != a2)) {
if ("asc".equals(direction)) {
return a1.compareTo(a2);
}
if ("desc".equals(direction)) {
return a2.compareTo(a1);
}
} else {
{
if ("asc".equals(direction)) {
if (null == a1) { return -1;}else { return 1;} }
if ("desc".equals(direction)) {
if (null == a1) {return 1;} else{ return -1; } }
}
}
}
} catch (Exception e) {
log.info("自定义字段排序失败" + e.getMessage());
}
return 1;
}).collect(Collectors.toList());
return li;
}
return list;
}
}