List 根据属性去重

    /**
     * list去重复(深) 并根据字段进行排序
     */
    public static <T> ArrayList<T> deduplicate(List<T> list, String filedName) {
        Set<T> set = new TreeSet<>(new Comparator<T>() {
            @Override
            public int compare(T o1, T o2) {
                String object1 = getValueByFiledName(o1,filedName);
                String object2 = getValueByFiledName(o2,filedName);
                return object1.compareTo(object2);
            }
        });
        set.addAll(list);
        return new ArrayList<>(set);
    }

    /**
     * 根据类的属性名获取值
     * @param object 目标类
     * @param name  目标字段
     * @return  返回该类中该字段的value
     */
    public static String getValueByFiledName(Object object,String name){
        String value = "";
        try {
            Class objectClass = object.getClass();
            Field field = objectClass.getDeclaredField(name);
            field.setAccessible(true);
            value = String.valueOf(field.get(object));
        } catch (Exception exc) {
            value = "";
        }
        return value;
    }

猜你喜欢

转载自blog.csdn.net/han317426731/article/details/82909677