项目中需要对一些数据进行排序,应用到了个比较强大的比较器,感觉还是很不错的,贴上代码:
比如我有一个People对象,里面有 name, age 等属性,
现在我有一个People的list列表,需要进行排序,如按name或者age排
好了,可以这么写:
这样就可以实现按 属性排序了
[b] 对以上comparator进行了优化,如果类型为int的数据应用以上方法会存在问题[/b]
public class XXXComparator<E> {
private final Logger log = Logger.getLogger(XXXComparator.class);
@SuppressWarnings({ "unchecked", "rawtypes" })
public void sort(List<E> list, final String method, final String sortType) {
// list 要比较的list 对象列表
// method传入相应的get方法签名
// sortType desc or asc
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
int ret = 0;
try {
Method m1 = ((E) a).getClass().getMethod(method, null);
Method m2 = ((E) b).getClass().getMethod(method, null);
if (sortType != null && "desc".equals(sortType)) {
ret = m2.invoke(((E) b), null).toString()
.compareTo(m1.invoke(((E) a), null).toString());
} else {
ret = m1.invoke(((E) a), null).toString()
.compareTo(m2.invoke(((E) b), null).toString());
}
} catch (NoSuchMethodException e) {
log.error(e);
} catch (InvocationTargetException e) {
log.error(e);
} catch (IllegalAccessException e) {
log.error(e);
}
return ret;
}
});
}
}
比如我有一个People对象,里面有 name, age 等属性,
现在我有一个People的list列表,需要进行排序,如按name或者age排
好了,可以这么写:
XXXComparator<People> sortList = new XXXComparator<People>();
String method = "getName"; //or 'getAge'
String orderByType = "desc";
sortList.sort(peopleList, method, orderByType);
这样就可以实现按 属性排序了
[b] 对以上comparator进行了优化,如果类型为int的数据应用以上方法会存在问题[/b]
public class XXXComparator<E> {
private final Logger log = Logger.getLogger(XXXComparator.class);
@SuppressWarnings({ "unchecked", "rawtypes" })
public void sort(List<E> list, final String methodName, final String sortType) {
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
int ret = 0;
try {
Method method = a.getClass().getMethod(methodName);
Object aResult = method.invoke(a);
Object bResult = method.invoke(b);
if (aResult == null) {
return -1;
}
if (bResult == null) {
return 1;
}
if (aResult instanceof String) {
String com1 = "desc".equals(sortType) ? (String) aResult : (String) bResult;
String com2 = "desc".equals(sortType) ? (String) bResult : (String) aResult;
log.info("aResult= " + aResult + "\nbResult= " + bResult);
return com1.toLowerCase().compareTo(com2.toLowerCase());
}
if (aResult instanceof Comparable) {
Comparable com1 = "desc".equals(sortType) ? (Comparable) aResult
: (Comparable) bResult;
Comparable com2 = "desc".equals(sortType) ? (Comparable) bResult
: (Comparable) aResult;
return com1.compareTo(com2);
}
} catch (NoSuchMethodException e) {
log.error(e);
} catch (InvocationTargetException e) {
log.error(e);
} catch (IllegalAccessException e) {
log.error(e);
}
return ret;
}
});
}
}