java - 将列表对象与其他对象排序
问题描述
假设我有两个班级
public class TestA{
TestB testB;
String text;
SecondTest secondTest;
.
.
.
}
public class TestB{
int a;
int b;
}
现在我有一个列表TestB
List<TestB> list1
如果我想对列表进行排序,我可以这样做:
list1.sort(Comparator.comparing(TestB::getA)
但是,如果我有一个TestA
List<TestA> list2
如何排序到 a 或 b (TestB) 的列表呢?
解决方案
这是一个有趣的问题。对于这种深度比较,我不知道有任何 Java“本机”解决方案。但一个想法是使用您自己的特定比较器:
List<TestA> list2 = Arrays.asList( new TestA(new TestB(2, 20)), new TestA(new TestB(1, 10)), new TestA(new TestB(3, 30)) );
list2.sort( getComparator() );
public Comparator<TestA> getComparator() {
return new Comparator<TestA>() {
@Override
public int compare(TestA obj1, TestA obj2) {
int obj1A = obj1.getTestB().getA();
int obj2A = obj2.getTestB().getA();
return Integer.compare(obj1A, obj2A);
}
};
}
当然,应该相应地处理空值。
推荐阅读
- javascript - 在弹出框的数据内容中选择元素的属性
- c# - 嘿,我需要有关此代码的更多信息
- css - 使用 sass 实时生成 css
- docker - 詹金斯、kubernetes、getaddrinfo EAI_AGAIN
- c - 如何修改我的代码以使其正常工作?
- javascript - node.js 和 websocket:是否有可能进入竞争状态?
- python-3.x - python3 tkinter event.x event.y 负值
- caliburn.micro - Caliburn.Micro 4.0 是否仍在使用引导程序?
- c# - 在 C# 中创建自己的小部件并添加到表中
- r - 如何在ggplot2中获得y轴上的百分比?