首页 > 解决方案 > 将列表对象与其他对象排序

问题描述

假设我有两个班级

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) 的列表呢?

标签: javasortingobject

解决方案


这是一个有趣的问题。对于这种深度比较,我不知道有任何 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);
            }
        };
    } 

当然,应该相应地处理空值。


推荐阅读