1. 程式人生 > >java List 根據某個欄位進行升降序排列

java List 根據某個欄位進行升降序排列

開發十年,就只剩下這套架構體系了! >>>   

 用法

List<Student> students = new ArrayList<Student>();
SortList<Student> sortList = new SortList<Student>();
sortList.Sort(students, "age", "desc");
/**
 * ClassName: SortList
 * Function:  list升降排序專用
 * Date:      2019-03-21 16:57
 * author     likaixuan
 * version    V1.0
 */
public class SortList<E> {
    public  void Sort(List<E> list, final String method, final String sort) {
        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 (sort != null && "desc".equals(sort))// 倒序
                        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 ne) {

                } catch (IllegalAccessException ie) {

                } catch (InvocationTargetException it) {

                }
                return ret;
            }
        });
    }
}