Home » Java » java – Sorting generic list of objects with nested objects variable as key-Exceptionshub

java – Sorting generic list of objects with nested objects variable as key-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment


I have a list of objects that I am sorting on the name of a given method. This level one sorting works fine. I have problems with sorting on a key that is a member of a nested object. Any suggestions would be helpful, here’s what I’ve got so far.

Example object with nested object

public class User{

    private String userName;
    private String userLastName;
    private UserDob userDob;


public class UserDob{
    private int year;
    private int month;
    private int day;

Trying to sort on UserDob.year does not work with the below solution.

public static <T> List<T> sortListOfObjects(T object, List<T> unsortedList, String key, char order) throws NoSuchMethodException {
        if(object == null || unsortedList == null || unsortedList.size() == 0){
            return null;

        Method[] methods = object.getClass().getDeclaredMethods();

        for(int i = 0; i < methods.length; i++){
            String methodName = methods[i].getName();
            if(methodName != null && methodName.equalsIgnoreCase("get" + key)){
                Function comparingMethodName = getObjectComparingMethod(methodName);

                Comparator comparator = Comparator.comparing(comparingMethodName);

                if(order == 'd'){
                    Collections.sort(unsortedList, comparator.reversed());
                    Collections.sort(unsortedList, comparator);


        return unsortedList;

    private static <T, U> Function<T, U> getObjectComparingMethod(String methodName) {
        return (T tClass)-> {
            Object returnObject = null;
            try {
                Method method = tClass.getClass().getMethod(methodName, new Class[]{});
                returnObject = method.invoke(tClass);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {

            return (U) returnObject;
How to&Answers: