java升序属性_java List Collections.sort 排序 支持 对象属性 普通数据类型 升序 降序 正序 倒序 排列...

packagecn.itcast.itcastweb.web.servlets;importjava.lang.reflect.Method;importjava.text.SimpleDateFormat;import java.util.*;public class ListComparator implementsComparator {publicListComparator() {

}publicListComparator(String methodName) {this.methodName =methodName;

}//空:普通的数据类型 非空:对象数据类型 取methodName返回值比较

String methodName;public Object getValue(Object bean, String methodName) throwsException {

Method getMethod= bean.getClass().getMethod(methodName, null);return getMethod.invoke(bean, null);

}public intcompare(Object obj1, Object obj2) {int val = -1;try{if (methodName == null) {

val=_compare(obj1, obj2);

}else{

val=_compare(getValue(obj1, methodName),

getValue(obj2, methodName));

}

}catch(Exception ex) {

ex.printStackTrace();

}returnval;

}public int _compare(Object obj1, Object obj2) throwsException {if (obj1 == null || obj2 == null)return obj1 == null ? -1 : 1;

Class cl=obj1.getClass();if (obj1 instanceofjava.lang.Comparable) {//byte int long float..number, date , boolean , char

Method getMethod = obj1.getClass().getMethod("compareTo",newClass[] { cl });return (Integer) getMethod.invoke(obj1, newObject[] { obj2 });

}return -1;

}

}//测试类

classListComparator {

Long id;publicLong getId() {returnid;

}public voidsetId(Long id) {this.id =id;

}public static voidmain(String[] args) {//普通数据类型 升序

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

List list= newArrayList();for (long i = 0; i < 5; i++) {

list.add(newDate(System.currentTimeMillis()+ (int) (Math.random() * 1000000000)));

}

ListComparator c= newListComparator();

Collections.sort(list, c);for (int i = 0; i < list.size(); i++) {

System.out.println(simpleDateFormat.format(list.get(i)));

}//对象数据类型 降序

List userList = newArrayList();

ListComparator test= newListComparator();

test.setId(null);

userList.add(test);for (long i = 0; i < 5; i++) {

test= newListComparator();

test.setId(i);

userList.add(test);

}

c= new ListComparator("getId");

Collections.sort(userList, Collections.reverseOrder(c));for (int i = 0; i < userList.size(); i++) {

System.out.println(userList.get(i).getId());

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值