zoukankan      html  css  js  c++  java
  • List对象排序通用方法

     1 import java.util.Collections;
     2 import java.util.Comparator;
     3 import java.util.List;
     4 import java.lang.reflect.Method;
     5 import java.lang.reflect.InvocationTargetException;
     6 /**
     7 * 通用排序
     8 */
     9 public class SortList<E>{    
    10     public void Sort(List<E> list, final String method, final String sort){
    11         Collections.sort(list, new Comparator() {            
    12             public int compare(Object a, Object b) {
    13                 int ret = 0;
    14                 try{
    15                     Method m1 = ((E)a).getClass().getMethod(method, null);
    16                     Method m2 = ((E)b).getClass().getMethod(method, null);
    17                     if(sort != null && "desc".equals(sort))//倒序
    18                         ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a), null).toString());    
    19                     else//正序
    20                         ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString());
    21                 }catch(NoSuchMethodException ne){
    22                     System.out.println(ne);
    23                 }catch(IllegalAccessException ie){
    24                     System.out.println(ie);
    25                 }catch(InvocationTargetException it){
    26                     System.out.println(it);
    27                 }
    28                 return ret;
    29             }
    30          });
    31     }
    32 }

    调用示例:

    1 List<UserInfo> list = new ArrayList<UserInfo>();
    2 //调用排序通用类
    3 SortList<UserInfo> sortList = new SortList<UserInfo>();
    4 //按userId排序
    5 sortList.Sort(list, "getUserId", "desc");
  • 相关阅读:
    ZeroMQ
    ps-lite源码解析
    RDMA
    MapReduce
    parameter server
    BytePS
    ELF程序头部及程序加载
    网络序与主机序
    CPU、CPU核与线程的关系
    chroot
  • 原文地址:https://www.cnblogs.com/liuxiaoke/p/3470497.html
Copyright © 2011-2022 走看看