1
   public class B {
              private String name;
              private String  value;

             //Setters and Get
       }        
       public class C {
             private String name;
             private String  value;
        //Setters and Get Methods
       }
        public class D {
             private String name;
             private String  value;
             //Setters and Get
        }
        public class A {
              private B b;
              private C c;
              private D d;
            // Setters and Get
         }
        public class  Example{
          List<A> a = new Array List<A>();
            //Lets assume a  will contain objects of class B, C and D
           a .sort( Comparator.comparing(A::getB().getName).thenComparing(A::getC().getName));

         }

Sort field from one pojo , then sort field by next pojo. Need to understand how to sort in this situation. Can we use Comparator.comparing ()in this case?

1 Answer 1

2

You can't use method refences like that, but you could just use lambda expressions:

a.sort(Comparator.comparing((A x) -> x.getB().getName())
                 .thenComparing(x -> x.getC().getName()));
Sign up to request clarification or add additional context in comments.

3 Comments

1) x.getB().getName()-- x should be type casted to Class A rite? 2) Should class A implement comparator? I am getting java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.Comparable
You need Comparator.comparing((A x) -> x.getB().getName()) .thenComparing(x -> x.getC().getName()), due to the limited type inference. @user3233289 it’s impossible to get that ClassCastException with what you have posted in your question.
Thank you!. That helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.