public class SortList<E>{
public int compareMap(Object a, Object b, final String method,final String type, final String sort){
long ret = 0;
try {
Method m1 = ((E)a).getClass().getMethod(method, null);
Method m2 = ((E)b).getClass().getMethod(method, null);
switch(type){
case "String":
if(sort != null && "desc".equals(sort)){//倒序
ret = String.valueOf(m2.invoke(((E)b), null)).compareTo(String.valueOf(m1.invoke(((E)a), null)));
}else{
ret = String.valueOf(m1.invoke(((E)a), null)).compareTo(String.valueOf(m2.invoke(((E)b), null)));
}
break;
case "Date":
if(sort != null && "desc".equals(sort)){//倒序
if((m2.invoke(((E)b), null))==null){
return -1;
}
if((m1.invoke(((E)a), null))==null){
return 1;
}
ret = ((Date)(m2.invoke(((E)b), null))).getTime()-((Date)(m1.invoke(((E)a), null))).getTime();
}else{
if((m1.invoke(((E)a), null))==null){
return -1;
}
if((m2.invoke(((E)b), null))==null){
return 1;
}
ret = ((Date)(m1.invoke(((E)a), null))).getTime()-((Date)(m2.invoke(((E)b), null))).getTime();
}
break;
case "Integer":
if(sort != null && "desc".equals(sort)){//倒序
ret = toNumber(String.valueOf(m2.invoke(((E)b), null))).compareTo(toNumber(String.valueOf(m1.invoke(((E)a), null))));
}else{
ret = toNumber(String.valueOf(m1.invoke(((E)a), null))).compareTo(toNumber(String.valueOf(m2.invoke(((E)b), null))));
}
break;
default:
if(sort != null && "desc".equals(sort)){//倒序
ret = String.valueOf(m2.invoke(((E)b), null)).compareTo(String.valueOf(m1.invoke(((E)a), null)));
}else{
ret = String.valueOf(m1.invoke(((E)a), null)).compareTo(String.valueOf(m2.invoke(((E)b), null)));
}
break;
}
} catch (Exception e) {
// TODO 自动生成的 catch 块
logger.error(e.getMessage()+":::"+Arrays.toString(e.getStackTrace()));
e.printStackTrace();
}
return (int)ret;
}
/**
* map 先放的条件优先
* method 'getId'
* type 'String'
* sort 'asc'
* @param list
* @param sortMap
* @param sort
*/
public void SortMuitledList(List<E> list, final List<Map<String,String>> sortMapList){
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
long ret = 0;
try{
for(Map<String,String> sortMap:sortMapList){
ret = compareMap((E)a,(E)b,sortMap.get("method"),sortMap.get("type"),sortMap.get("sort"));
if(ret!=0){
return (int)ret;
}
}
}catch(Exception e){
logger.error(e.getMessage()+":::"+Arrays.toString(e.getStackTrace()));
}
return (int)ret;
}
});
}
}
使用方法
SortList<TestVO> sort=new SortList<>();
List<TestVO> list=new ArrayList<>();
TestVO t1=new TestVO("1","1","1",DateUtil.stringToDate(2, "2018-05-04 09:00:00"));
TestVO t2=new TestVO("2","2","2",DateUtil.stringToDate(2, "2018-05-04 10:00:00"));
TestVO t3=new TestVO("3","2","2",DateUtil.stringToDate(2, "2018-05-04 08:00:00"));
list.add(t1);
list.add(t2);
list.add(t3);
LinkedHashMap<String, String> sortMap = new LinkedHashMap<>();
sortMap.put("getTime", "Date");
sortMap.put("getId", "String");
sort.SortMuitled(list, sortMap, "asc");
根据放入map顺序,优先第一个条件,第一条件相同按第二条件排