将列表对象与另一个对象排序

huangapple go评论57阅读模式
英文:

Sort List Object with another objects

问题

如果我有两个类:

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)进行排序呢?

英文:

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&lt;TestB&gt; 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&lt;TestA&gt; list2
How I sort to a or b (TestB)?

答案1

得分: 0

那是一个有趣的问题。
我不知道有没有任何 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);
            }
        };
    } 

当然,空值应该得到相应的处理。

英文:

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&lt;TestA&gt; 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&lt;TestA&gt; getComparator() {      
        return new Comparator&lt;TestA&gt;() {
            @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.

huangapple
  • 本文由 发表于 2020年8月27日 22:34:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63618329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定