我们在开发过程中经常会遇到排序的需求,常见的有通过日期、数字、英文首字母。
为了便于大家开发,省略重写compare方法,下面为大家提供一个排序工具类
上代码:
package com.xxx.web.common.utils;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class ListSortUtils {
public static <T> List<T> listSort(List<T> list, final String methodName) {
Collections.sort(list, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
try {
Method m1 = ((T) o1).getClass().getMethod(methodName);
Method m2 = ((T) o2).getClass().getMethod(methodName);
String typeName = m1.invoke(o1).getClass().getName();
if ("java.lang.Integer".equals(typeName)){
Integer num1=new Integer(String.valueOf(m1.invoke(o1)));
Integer num2=new Integer(String.valueOf(m2.invoke(o2)));
return num1.compareTo(num2);
}else if ("java.util.Date".equals(typeName)){
Date dt1=(Date) m1.invoke(o1);
Date dt2=(Date) m2.invoke(o2);
Long time1=dt1.getTime();
Long time2=dt2.getTime();
return time1.compareTo(time2);
}else if ("java.lang.String".equals(typeName)){
String str1=String.valueOf(m1.invoke(o1));
String str2=String.valueOf(m2.invoke(o2));
return str1.compareTo(str2);
}
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
});
return list;
}
}
测试泛型类:
package com.xxx.web.offer.domain;
public class ConfigDO{
private String key;
private Object value;
public String getKey(){
return key;
}
public void setKey(String key){
this.key = key;
}
public Object getValue(){
return value;
}
public void setValue(String value){
this.value = value;
}
public ConfigDO(String key, Object value){
this.key = key;
this.value = value;
}
}
调动代码如下:
List<ConfigDO> list = new ArrayList();
//此处省略list构造过程
list = listSort(list, "getKey");