使用其他对象对列表对象进行排序 [英] Sort List Object with another objects

查看:45
本文介绍了使用其他对象对列表对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个类

public class TestA{
   TestB testB;
   String text;
   SecondTest secondTest;
               .
               .
               .
}

public class TestB{
   int a;
   int b;
}

现在我有一个带有 TestB List 的列表list1

如果我想对列表进行排序,我可以这样做:

If I want to sort the list I can do something like this:

list1.sort(Comparator.comparing(TestB::getA)

但是如果我有一个带有 TestA List 的列表怎么办?list2我如何排序为 a 或 b (TestB)?

But what if I have a List with TestA List<TestA> list2 How I sort to a or b (TestB)?

推荐答案

这是一个有趣的问题.我不知道有任何 Java 本机"这种深度比较的解决方案.但一种想法是使用您自己的特定比较器:

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.

这篇关于使用其他对象对列表对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆