List按照指定字段排序

xiaoxiao2021-02-28  84

一般我们常用的List排序是 Collections.sort(list);但是如果list装的对象,要按照对象字段排序的话这是不支持的。

下面这个是我自己其他博客看见的。

List<User> list = new ArrayList<>(); // 按照user实体类的createTime倒序 Comparator<User> comparator = (t1, t2) -> t1.getCreateTime().compareTo(t2.getCreateTime()); list.sort(comparator.reversed());

我自己融合Java8 写了一个工具类,上传到了github,有兴趣的可以交流一下。

/** * * 按照指定对象的字段排序(正序) * * @param list * @param param 排序字段 * @param <T> * @throws IntrospectionException */ public static final <T> void ObjSort(List<T> list , String param) throws IntrospectionException { Collections.sort(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { Class<?> type = o1.getClass(); PropertyDescriptor descriptor1 = null; try { descriptor1 = new PropertyDescriptor( param, type ); Method readMethod1 = descriptor1.getReadMethod(); PropertyDescriptor descriptor2 = new PropertyDescriptor( param, type ); Method readMethod2 = descriptor2.getReadMethod(); return readMethod1.invoke(o1).toString().compareTo(readMethod2.invoke(o2).toString()); } catch (IntrospectionException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return -1; } }); }

倒叙的话也非常简单,在代码里加了reversed();

/** * * 按照指定对象的字段倒叙排序 * * @param list * @param param 排序字段 * @param <T> * @throws IntrospectionException */ public static final <T> void ObjSortReversed(List<T> list, String param) throws IntrospectionException { Collections.sort(list, new Comparator<T>() { @Override public int compare(T o1, T o2) { Class<?> type = o1.getClass(); PropertyDescriptor descriptor1 = null; try { descriptor1 = new PropertyDescriptor( param, type ); Method readMethod1 = descriptor1.getReadMethod(); PropertyDescriptor descriptor2 = new PropertyDescriptor( param, type ); Method readMethod2 = descriptor2.getReadMethod(); return readMethod1.invoke(o1).toString().compareTo(readMethod2.invoke(o2).toString()); } catch (IntrospectionException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return -1; } }.reversed()); } public static final Boolean isEmpty(Collection<?> collection){ return (collection == null || collection.isEmpty()); }

其实spring提供了很多工具,只是我们经常都忽略了。我是一个小小新手,有时候会去看看这些东西~然后写一些项目上会常用的util传到github上。如果有更好的想法可以和我交流一下,让我多多学习一下。哈哈哈

转载请注明原文地址: https://www.6miu.com/read-40033.html

最新回复(0)