How to sort a List<Object> alphabetically using Object name field

后端 未结 16 1496
暗喜
暗喜 2020-11-28 06:00

I have a List of Objects like List p.I want to sort this list alphabetically using Object name field. Object contains 10 field and name field is o
16条回答
  •  旧时难觅i
    2020-11-28 06:26

    Here is a version of Robert B's answer that works for List and sorting by a specified String property of the object using Reflection and no 3rd party libraries

    /**
     * Sorts a List by the specified String property name of the object.
     * 
     * @param list
     * @param propertyName
     */
    public static  void sortList(List list, final String propertyName) {
    
        if (list.size() > 0) {
            Collections.sort(list, new Comparator() {
                @Override
                public int compare(final T object1, final T object2) {
                    String property1 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object1);
                    String property2 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object2);
                    return property1.compareToIgnoreCase (property2);
                }
            });
        }
    }
    
    
    public static Object getSpecifiedFieldValue (String property, Object obj) {
    
        Object result = null;
    
        try {
            Class objectClass = obj.getClass();
            Field objectField = getDeclaredField(property, objectClass);
            if (objectField!=null) {
                objectField.setAccessible(true);
                result = objectField.get(obj);
            }
        } catch (Exception e) {         
        }
        return result;
    }
    
    public static Field getDeclaredField(String fieldName, Class type) {
    
        Field result = null;
        try {
            result = type.getDeclaredField(fieldName);
        } catch (Exception e) {
        }       
    
        if (result == null) {
            Class superclass = type.getSuperclass();     
            if (superclass != null && !superclass.getName().equals("java.lang.Object")) {       
                return getDeclaredField(fieldName, type.getSuperclass());
            }
        }
        return result;
    }
    

提交回复
热议问题