I want to sort a list of my POJO by a property that is also a POJO. The Comparator should move null
values to the end of the list. The null
s are already at second POJO level.
Assume following POJOs:
public class Foo {
private Bar bar;
private boolean set;
// getter and setter omitted
}
public class Bar {
private String name1;
private String name2;
// getter and setter omitted
}
Now I have a List<Foo>
which should be sorted by Bar#name1
.
So far I have following code:
Collections.sort(fullList, Comparator.comparing(Foo::getBar::getName1,
Comparator.nullsLast(Comparator.naturalOrder())));
This sadly doesn't work, as the ::
operator can't be chained. So I updated Bar
class to implement Comparator<Bar>
public class Bar implements Comparator<Bar> {
private String name1;
private String name2;
// getter and setter omitted
@Override
public int compare(Bar o1, Bar o2) {
return o1.getName1().compareTo(o2.getName1());
}
}
and changed my sorting code to:
Collections.sort(fullList, Comparator.comparing(Foo::getBar,
Comparator.nullsLast(Comparator.naturalOrder())));
But this gives me compilation errors:
The method comparing(Function, Comparator) in the type Comparator is not applicable for the arguments (Foo::getBar, Comparator>>)
as well as
The type Foo does not define getBar(T) that is applicable here
What am I doing wrong on my second part? How do I fix it?
EDIT:
I just realized that a crucial part is missing.
In the list, Foo
s are never null
, but Bar
might be null
. In the case that Bar
is null
, the Foo
should be moved to the end of the list.