Sort List Object with another objects

二次信任 提交于 2021-01-28 08:47:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!