Java 8对多个对象进行排序

时间:2019-03-19 17:44:50

标签: java sorting java-8

   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));

         }

从一个pojo中排序字段,然后按下一个pojo排序字段。     需要了解在这种情况下如何排序。我们可以用吗     在这种情况下是Comparator.comparing()?

1 个答案:

答案 0 :(得分:2)

您不能使用这样的方法引用,但只能使用lambda表达式:

a.sort(Comparator.comparing((A x) -> x.getB().getName())
                 .thenComparing(x -> x.getC().getName()));