Reputation: 9247
I have List of some objects. And i want to order by some property and nulls first, such as in query:
select * from aaa order by ext_id nulls first;
I know when i have list of string i can do this:
List<String> names2 = Arrays.asList("XML", null, "Java", "HTML", "CSS");
names2.sort(Comparator.nullsFirst(String::compareTo));
But what when i have List of some objects of class?
Any suggestion how can i achive that in java?
Upvotes: 0
Views: 238
Reputation: 88
You can do that, for example:
public static void main(String[] args) {
A a1 = new A();
a1.setName("A");
A a2 = new A();
a2.setName("B");
A anull = null;
List<A> list = new ArrayList<>();
list.add(a1);
list.add(a2);
list.add(anull);
list.sort(nullsFirst(
comparing(A::getName, nullsFirst(naturalOrder()))));
list.forEach(System.out::println);
}
public static class A {
String name;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
Upvotes: 1