[英]Java sorting with Comparator and Inner classes
Given this combination of Java classes: 鉴于Java类的这种组合:
public class OuterClass
{
public String field01;
public int field02;
public InnerClass innerField
// ...getters, setters
public class InnerClass
{
public int innerField01;
public BigDecimal innerField02;
// ...getters, setters
I want to order them by outer and inner fields. 我想按外部和内部字段排序。 Now, given a
List<OuterClass> list
, I can easily sort that by eg, field01
with: 现在,给定一个
List<OuterClass> list
,我可以很容易地通过例如field01
进行排序:
Collections.sort(list, Comparator.comparing(OuterClass::getField01));
But which way may I sort by InnerClass.innerfield.innerfield01
? 但是,我可以按哪种方式对
InnerClass.innerfield.innerfield01
排序? I tried 我试过了
Collections.sort(list, Comparator.comparing(OuterClass::InnerField::innerField01));
and few other ways, but with no success. 和其他几种方法,但没有成功。 Maybe I should use in some way
OuterClass::new
, but I don't know how. 也许我应该以某种方式使用
OuterClass::new
,但是我不知道如何使用。
Let both outer and inner class implement Comparable
and add a compareTo
method to both or just let outer class implement it and handle all comparison there. 让外部类和内部类都实现
Comparable
并向两者都添加compareTo
方法,或者让外部类实现它并在那里处理所有比较。 Which way is best depends on how you want to compare, in the below example Outer is sorted first, then Inner 哪种方法最好取决于您要如何比较,在下面的示例中,先对外部排序,然后对内部排序
public class OuterClass implements Comparable{
public String field01;
public int field02;
public InnerClass innerField;
public class InnerClass implements Comparable {
public int innerField01;
public BigDecimal innerField02;
@Override
public int compareTo(Object o) {
//...
}
}
@Override
public int compareTo(Object o) {
OuterClass obj = (OuterClass)o;
int res = field01.compareTo(obj.field01);
if (res != 0) {
return res;
}
return this.innerField.compareTo(obj.innerField);
}
}
You could use Comparator.comparing(Function, Comparator) like this: 您可以像这样使用Comparator.comparing(Function,Comparator) :
Collections.sort(list,
Comparator.comparing(OuterClass::getInnerField,
Comparator.comparingInt(InnerClass::getInnerField01)));
The first argument is the function used to extract the key on which you want to sort. 第一个参数是用于提取要排序的键的函数。 In your case: the
Innerfield
from the OuterClass
. 你的情况:在
Innerfield
从OuterClass
。
The second argument is the Comparator used to compare the sort key. 第二个参数是用于比较排序键的Comparator。 In your case: a
Comparator
for one of the fields of the InnerField
( innerField01
in the example above). 在你的情况:一个
Comparator
对的字段之一InnerField
( innerField01
在上面的例子)。
Collections.sort(list, Comparator.comparing(obj -> obj.getInnerField().getInnerField01()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.