手写比较器comparator

项目中需要对一些数据进行排序,应用到了个比较强大的比较器,感觉还是很不错的,贴上代码:



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;
}
});
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值