Reputation: 1874
Given this combination of Java classes:
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 e.g., field01
with:
Collections.sort(list, Comparator.comparing(OuterClass::getField01));
But which way may I sort by 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.
Upvotes: 0
Views: 2626
Reputation: 2344
You could use Comparator.comparing(Function, Comparator) like this:
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
.
The second argument is the Comparator used to compare the sort key. In your case: a Comparator
for one of the fields of the InnerField
(innerField01
in the example above).
Upvotes: 5
Reputation: 155
Collections.sort(list, Comparator.comparing(obj -> obj.getInnerField().getInnerField01()));
Upvotes: -1
Reputation: 51973
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. 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);
}
}
Upvotes: 1