问题
Assume I have two Classes
public class TestA{
TestB testB;
String text;
SecondTest secondTest;
.
.
.
}
public class TestB{
int a;
int b;
}
Now I have a List with TestB
List<TestB> list1
If I want to sort the list I can do something like this:
list1.sort(Comparator.comparing(TestB::getA)
But what if I have a List with TestA
List<TestA> list2
How I sort to a or b (TestB)?
回答1:
That's an interesting question. I don't know of any Java "native" solution for this kind of deep comparison. But one idea is to use your own specific Comparator:
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);
}
};
}
Of couse null values should be handled accordingly.
来源:https://stackoverflow.com/questions/63618329/sort-list-object-with-another-objects