关于 List 里自定义对象的排序

现在用 List 对象里的属性进行排序。

    以下为了通用,使用了反射。


TempProductInfoEntity为临时存储的实体对象。

 

/**

    * 暂时用来对 List 里的对象根据对象属性排序

    * @author Ja0ck5

    */

   public void sort(List<? extends Object> list,final String comp ,final String sort){

       Collections.sort(list,new Comparator<Object>() {

         public int compare(Object a,Object b) {

           int result = 0;

           String methodName = null;

           StringBuilder sb = newStringBuilder(comp);

           try {

              if(StringUtil.isNotEmpty(comp)){

             

              sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));

              methodName=sb.insert(0, "get").toString();

             

             

            Method meth1 = ((TempProductInfoEntity)a).getClass().getDeclaredMethod(methodName);

            Method meth2 =((TempProductInfoEntity)a).getClass().getDeclaredMethod(methodName);

           

            if(meth1 != null && meth2 != null){

            Object compO1=meth1.invoke((TempProductInfoEntity)a);

            Object compO2=meth2.invoke((TempProductInfoEntity)b);

                  if(compO1 !=null && compO2!=null){

                     if("desc".equals(sort)){

                        result= compO1.toString().compareTo(compO2.toString());

                     }else{

                        result= compO1.toString().compareTo(compO2.toString());

                     }

                  

                  }

            }

              }

         } catch (NoSuchMethodException | SecurityException e) {

            throw new java.lang.RuntimeException(e);

         } catch (IllegalAccessException e) {

            throw new java.lang.RuntimeException(e);

         } catch (IllegalArgumentException e) {

            throw new java.lang.RuntimeException(e);

         } catch (InvocationTargetException e) {

            throw new java.lang.RuntimeException(e);

         }

         return result;

     }

      

   });

      

   }






代码略微冗余,希望看客们指点指点,只为了成为更优雅的人微笑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值