gpt4 book ai didi

Java 8 对多个对象进行排序

转载 作者:行者123 更新时间:2023-11-30 01:53:31 24 4
gpt4 key购买 nike

   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 () ?

最佳答案

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

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

关于Java 8 对多个对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55247068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com