List<Object>集合按照Object的某个字段排序,解决取不到父类字段问题

<p>最近在做一个项目,里边有大量的排序需求,神烦!如果每个排序需求都做一个接口的话,那样工作量就太大了,所以就要有一个通用一些的排序工具类,来解决排序问题。</p><p>由于排序需求很大一部分都是List集合排序,所以就从网上找了一个List<Object>集合排序工具类来使用,这个工具类可以很灵活的传入需要排序的字段和需要的升序或者降序来排序。</p>
public class SortListUtil {

    public static final String DESC = "desc";
    public static final String ASC = "asc";

    /**
     * 对list中的元素按升序排列.
     *
     * @param list
     *            排序集合
     * @param field
     *            排序字段
     * @return
     */
    public static List<?> sort(List<?> list, final String field) {
        return sort(list, field, null);
    }

    /**
     * 对list中的元素进行排序.
     *
     * @param list
     *            排序集合
     * @param field
     *            排序字段
     * @param sort
     *            排序方式: SortList.DESC(降序) SortList.ASC(升序).
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<?> sort(List<?> list, final String field,
                               final String sort) {
        Collections.sort(list, new Comparator() {
            public int compare(Object a, Object b) {
                int ret = 0;
                try {

                    Field f = null;
                    //a.getClass().getDeclaredField(field);只能获取当前对象的字段,不能获取父类的字段
                    //以下为循环获取父类的字段
                    Class<?> clazz = a.getClass() ;
                    for(; clazz != Object.class ; clazz = clazz.getSuperclass()) {
                        try {
                            f = clazz.getDeclaredField(field) ;
                            break;
                        } catch (Exception e) {
                            //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
                            //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
                        }
                    }
                    //Field f = a.getClass().getDeclaredField(field);
                    f.setAccessible(true);
                    Class<?> type = f.getType();

                    if (type == int.class) {
                        ret = ((Integer) f.getInt(a)).compareTo((Integer) f
                                .getInt(b));
                    } else if (type == double.class) {
                        ret = ((Double) f.getDouble(a)).compareTo((Double) f
                                .getDouble(b));
                    } else if (type == long.class) {
                        ret = ((Long) f.getLong(a)).compareTo((Long) f
                                .getLong(b));
                    } else if (type == float.class) {
                        ret = ((Float) f.getFloat(a)).compareTo((Float) f
                                .getFloat(b));
                    } else if (type == Date.class) {
                        ret = ((Date) f.get(a)).compareTo((Date) f.get(b));
                    } else if (isImplementsOf(type, Comparable.class)) {
                        ret = ((Comparable) f.get(a)).compareTo((Comparable) f
                                .get(b));
                    } else {
                        ret = String.valueOf(f.get(a)).compareTo(
                                String.valueOf(f.get(b)));
                    }

                }catch (Exception e) {
                    e.printStackTrace();
                }
                if (sort != null && sort.toLowerCase().equals(DESC)) {
                    return -ret;
                } else {
                    return ret;
                }

            }
        });
        return list;
    }

    /**
     * 对list中的元素进行排序.
     *
     * @param list
     *            排序集合
     * @param field
     *            排序字段
     * @param sort
     *            排序方式: SortList.DESC(降序) SortList.ASC(升序).
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<?> sortMapList(List<?> list, final String field,
                               final String sort) {
        Collections.sort(list, new Comparator() {
            public int compare(Object a, Object b) {
                int ret = 0;
                try {
                    Map<String,Object> tempA = (Map<String,Object>)a;
                    Map<String,Object> tempB = (Map<String,Object>)b;
                    Object fA = tempA.get(field);
                    Object fB = tempB.get(field);
                    if(fA instanceof String){
                        fA = Double.parseDouble((String)fA);
                    }
                    if(fB instanceof String){
                        fB = Double.parseDouble((String)fB);
                    }
                    ret = ((Double)fA).compareTo((Double)fB);
                }catch (Exception e) {
                    e.printStackTrace();
                }
                if (sort != null && sort.toLowerCase().equals(DESC)) {
                    return -ret;
                } else {
                    return ret;
                }

            }
        });
        return list;
    }

    /**
     * 对list中的元素按fields和sorts进行排序,
     * fields[i]指定排序字段,sorts[i]指定排序方式.如果sorts[i]为空则默认按升序排列.
     *
     * @param list
     * @param fields
     * @param sorts
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<?> sort(List<?> list, String[] fields, String[] sorts) {
        if (fields != null && fields.length > 0) {
            for (int i = fields.length - 1; i >= 0; i--) {
                final String field = fields[i];
                String tmpSort = ASC;
                if (sorts != null && sorts.length > i && sorts[i] != null) {
                    tmpSort = sorts[i];
                }
                final String sort = tmpSort;
                Collections.sort(list, new Comparator() {
                    public int compare(Object a, Object b) {
                        int ret = 0;
                        try {
                            Field f = a.getClass().getDeclaredField(field);
                            f.setAccessible(true);
                            Class<?> type = f.getType();
                            if (type == int.class) {
                                ret = ((Integer) f.getInt(a))
                                        .compareTo((Integer) f.getInt(b));
                            } else if (type == double.class) {
                                ret = ((Double) f.getDouble(a))
                                        .compareTo((Double) f.getDouble(b));
                            } else if (type == long.class) {
                                ret = ((Long) f.getLong(a)).compareTo((Long) f
                                        .getLong(b));
                            } else if (type == float.class) {
                                ret = ((Float) f.getFloat(a))
                                        .compareTo((Float) f.getFloat(b));
                            } else if (type == Date.class) {
                                ret = ((Date) f.get(a)).compareTo((Date) f
                                        .get(b));
                            } else if (isImplementsOf(type, Comparable.class)) {
                                ret = ((Comparable) f.get(a))
                                        .compareTo((Comparable) f.get(b));
                            } else {
                                ret = String.valueOf(f.get(a)).compareTo(
                                        String.valueOf(f.get(b)));
                            }

                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }

                        if (sort != null && sort.toLowerCase().equals(DESC)) {
                            return -ret;
                        } else {
                            return ret;
                        }
                    }
                });
            }
        }
        return list;
    }

    /**
     * 默认按正序排列
     *
     * @param list
     * @param method
     * @return
     */
    public static List<?> sortByMethod(List<?> list, final String method) {
        return sortByMethod(list, method, null);
    }

    @SuppressWarnings("unchecked")
    public static List<?> sortByMethod(List<?> list, final String method,
                                       final String sort) {
        Collections.sort(list, new Comparator() {
            public int compare(Object a, Object b) {
                int ret = 0;
                try {
                    Method m = a.getClass().getMethod(method, null);
                    m.setAccessible(true);
                    Class<?> type = m.getReturnType();
                    if (type == int.class) {
                        ret = ((Integer) m.invoke(a, null))
                                .compareTo((Integer) m.invoke(b, null));
                    } else if (type == double.class) {
                        ret = ((Double) m.invoke(a, null)).compareTo((Double) m
                                .invoke(b, null));
                    } else if (type == long.class) {
                        ret = ((Long) m.invoke(a, null)).compareTo((Long) m
                                .invoke(b, null));
                    } else if (type == float.class) {
                        ret = ((Float) m.invoke(a, null)).compareTo((Float) m
                                .invoke(b, null));
                    } else if (type == Date.class) {
                        ret = ((Date) m.invoke(a, null)).compareTo((Date) m
                                .invoke(b, null));
                    } else if (isImplementsOf(type, Comparable.class)) {
                        ret = ((Comparable) m.invoke(a, null))
                                .compareTo((Comparable) m.invoke(b, null));
                    } else {
                        ret = String.valueOf(m.invoke(a, null)).compareTo(
                                String.valueOf(m.invoke(b, null)));
                    }

                    if (isImplementsOf(type, Comparable.class)) {
                        ret = ((Comparable) m.invoke(a, null))
                                .compareTo((Comparable) m.invoke(b, null));
                    } else {
                        ret = String.valueOf(m.invoke(a, null)).compareTo(
                                String.valueOf(m.invoke(b, null)));
                    }

                }catch (Exception it) {
                    System.out.println(it);
                }

                if (sort != null && sort.toLowerCase().equals(DESC)) {
                    return -ret;
                } else {
                    return ret;
                }
            }
        });
        return list;
    }

    @SuppressWarnings("unchecked")
    public static List<?> sortByMethod(List<?> list, final String methods[],
                                       final String sorts[]) {
        if (methods != null && methods.length > 0) {
            for (int i = methods.length - 1; i >= 0; i--) {
                final String method = methods[i];
                String tmpSort = ASC;
                if (sorts != null && sorts.length > i && sorts[i] != null) {
                    tmpSort = sorts[i];
                }
                final String sort = tmpSort;
                Collections.sort(list, new Comparator() {
                    public int compare(Object a, Object b) {
                        int ret = 0;
                        try {
                            Method m = a.getClass().getMethod(method, null);
                            m.setAccessible(true);
                            Class<?> type = m.getReturnType();
                            if (type == int.class) {
                                ret = ((Integer) m.invoke(a, null))
                                        .compareTo((Integer) m.invoke(b, null));
                            } else if (type == double.class) {
                                ret = ((Double) m.invoke(a, null))
                                        .compareTo((Double) m.invoke(b, null));
                            } else if (type == long.class) {
                                ret = ((Long) m.invoke(a, null))
                                        .compareTo((Long) m.invoke(b, null));
                            } else if (type == float.class) {
                                ret = ((Float) m.invoke(a, null))
                                        .compareTo((Float) m.invoke(b, null));
                            } else if (type == Date.class) {
                                ret = ((Date) m.invoke(a, null))
                                        .compareTo((Date) m.invoke(b, null));
                            } else if (isImplementsOf(type, Comparable.class)) {
                                ret = ((Comparable) m.invoke(a, null))
                                        .compareTo((Comparable) m.invoke(b,
                                                null));
                            } else {
                                ret = String.valueOf(m.invoke(a, null))
                                        .compareTo(
                                                String.valueOf(m
                                                        .invoke(b, null)));
                            }

                        } catch (NoSuchMethodException ne) {
                            System.out.println(ne);
                        } catch (IllegalAccessException ie) {
                            System.out.println(ie);
                        } catch (InvocationTargetException it) {
                            System.out.println(it);
                        }

                        if (sort != null && sort.toLowerCase().equals(DESC)) {
                            return -ret;
                        } else {
                            return ret;
                        }
                    }
                });
            }
        }
        return list;
    }

    /**
     * 判断对象实现的所有接口中是否包含szInterface
     *
     * @param clazz
     * @param szInterface
     * @return
     */
    public static boolean isImplementsOf(Class<?> clazz, Class<?> szInterface) {
        boolean flag = false;

        Class<?>[] face = clazz.getInterfaces();
        for (Class<?> c : face) {
            if (c == szInterface) {
                flag = true;
            } else {
                flag = isImplementsOf(c, szInterface);
            }
        }

        if (!flag && null != clazz.getSuperclass()) {
            return isImplementsOf(clazz.getSuperclass(), szInterface);
        }

        return flag;
    }

    //根据MAP的值进行排序
    public static Map<String, Object> sortMapByValue(Map<String, Object> oriMap) {
        Map<String, Object> sortedMap = new LinkedHashMap<String, Object>();
        if (oriMap != null && !oriMap.isEmpty()) {
            List<Map.Entry<String, Object>> entryList = new ArrayList<Map.Entry<String, Object>>(oriMap.entrySet());
            Collections.sort(entryList,
                    new Comparator<Map.Entry<String, Object>>() {
                        public int compare(Map.Entry<String, Object> entry1,
                                           Map.Entry<String, Object> entry2) {
                            int value1 = 0, value2 = 0;
                            try {
                                value1 = getInt(entry1.getValue());
                                value2 = getInt(entry2.getValue());
                            } catch (NumberFormatException e) {
                                value1 = 0;
                                value2 = 0;
                            }
                            return value2 - value1;
                        }
                    });
            Iterator<Map.Entry<String, Object>> iter = entryList.iterator();
            Map.Entry<String, Object> tmpEntry = null;
            while (iter.hasNext()) {
                tmpEntry = iter.next();
                sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
            }
        }
        return sortedMap;
    }

    private static int getInt(Object str) {
        int i = 0;
        try {
            Pattern p = Pattern.compile("^\\d+");
            Matcher m = p.matcher(str.toString());
            if (m.find()) {
                i = Integer.valueOf(m.group());
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return i;
    }
}
时间: 2024-10-30 21:05:45

List<Object>集合按照Object的某个字段排序,解决取不到父类字段问题的相关文章

c# 对List&lt;T&gt; 某字段排序,取TOP条数据

//排序的对象里的字段数据准备 try { cmr.v4 = Double.Parse(cmr.v3) - Double.Parse(cmr.v2); } catch (Exception e) { }  cmjList.Add(cmr); //建立临时List<T> List<CModelJunction> cmjList_showtab = new List<CModelJunction>();//用于显示在右上表格中的junction 100条 //排序后取TOP

sql 多个字段排序,头一个字段排序完,再对第二个字段进行排序(以此类推)

现根据num排序,num数字相同的根据时间进行排序,都是降序DESC SELECT * FROM counts ORDER BY num DESC,create_time DESC

JAVA List根据字段排序以及取前几条数据

1.经常会遇到对组装的list排序或提取list中前几条数据,例如: 根据时间排序: 1 list.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime())); 取list前几条数据: 1 List newList = list.subList(start,end); start, end 指从第几个开始到第几个结束. 原文地址:https://www.cnblogs.com/wang-yaz/p/8406022.html

对List&lt;Map&lt;String, Object&gt;&gt;集合排序

private void mySort(List<Map<String, Object>> list) { //list为待排序的集合,按SEQ字段排序 Comparator<Map<String, String>> mapComprator = new Comparator<Map<String, String>>() { @Override public int compare(Map<String, String>

Math对象是个organizational object(集合的对象)

Math对象是个organizational object(集合的对象),它只是数学相关的公用方法与常量的集合.Math对象中没有变量,即这个对象没有状态——不能用于存储任何事物.它唯一包含的数据只是几个常量,例如PI(3.14).不过,Math对象的方法很好用.例如random()方法就能产生介于0与1之间的随机数.

How to cast List&lt;Object&gt; to List&lt;MyClass&gt; Object集合转换成实体集合

List<Object> list = getList(); return (List<Customer>) list; Compiler says: cannot cast List<Object> to List<Customer> 不能将Object集合强制转换成实体集合! you can always cast any object to any type by up-casting it to Object first. in your case:

随机获取部分List&lt;Object&gt;集合

随机返回list对象 /** * 返回随机List * @param list 备选 * @param selected 备选数量 * @return */ public List getRandomNum(List list, int selected) { List<Object> reList = new ArrayList<Object>(); Random random = new Random(); // 先抽取,备选数量的个数 if (list.size() >

关于List&lt;Map&lt;String,Object&gt;&gt;集合 的按大小排序

今天写项目,突然遇到了一个问题.程序要求我把一个List<Map<String,Object>>集合按大小排序,卧槽,当时我就懵逼了~        经过研究,功夫不负有心人啊,叼叼哒的我肿么把这个排序搞定了,回头发现,代码也是叼叼哒~醉了醉了~        废话不多说,直接上代码://这是你自己用来接受查询出来的数据的集合. List<Map<String,Object>> listMap1 = new LinkedList<Map<Stri

Redis存储Object 和 list&lt;object&gt;

Redis 存储支持的类型没有object ,虽然有支持list,但是只支持List<String> 有两种方法可以实现存储对象和泛型 1.用序列化和反序列化 2.json 序列化工具类,实现序列化和反序列话对象和list集合 package com; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.Object