I have a list of entities Entity
with the fields id
and createdDate
. I want to sort them as following:
id
firstid
null, most recent createdDate
firstI've tried the following unsuccessfuly, as it throwns a NullPointerException
when id
is null
Comparator comp = Comparator
.nullsFirst(Comparator.comparing(e -> ((Entity) e).getId()))
.thenComparing(e -> ((Entity e).getCreatedDate())
.reversed();
entities.stream().sorted(comp).findFirst();
For what I see, Comparator.nullsFirst
handles when the entity is null, not when the field to be compared is null. How can I handle this situation?
We can simply compare the string with Null using == relational operator. Print true if the above condition is true. Else print false.
Say you have a table with a NULLable column type, and you want to find rows with a NULL value in that column. Since you can't use a equality operator in the WHERE clause (remember, NULL values can't be equated or compared), the right way to compare NULL values is to use the IS and IS NOT operators.
out. println("(Object)string == number: " + ((Object)string == number)); To conclude this post and answer the titular question Does null equal null in Java? the answer is a simple yes.
I think you are looking for comparator like this, using Comparator.nullsLast
:
Comparator<MyClass> comparator = Comparator.comparing(MyClass::getId, Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(MyClass::getCreateDate);
The code to test it :
List<MyClass> list = new ArrayList<>();
list.add(new MyClass(null, LocalDate.now()));
list.add(new MyClass(4L, LocalDate.now()));
list.add(new MyClass(2L, LocalDate.now()));
list.add(new MyClass(4L, LocalDate.now().plusDays(1)));
list.add(new MyClass(null, LocalDate.now().plusDays(1)));
Comparator<MyClass> comparator = Comparator.comparing(MyClass::getId, Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(MyClass::getCreateDate);
list.stream().sorted(comparator).forEach(myClass -> System.out.println(myClass.id + " " + myClass.createDate));
The output is :
4 2019-06-14
4 2019-06-15
2 2019-06-14
null 2019-06-14
null 2019-06-15
If you want nulls
to be first just change nullsLast
to nullsFirst
.
Extending @Mena's comment:
java.util.Collections.sort(entities, new Comparator<Entity>(){
@Override
public int compare(Entity ent1, Entity ent2) {
Object id1=ent1.getId();
Object id2 = ent2.getId();
if (id1!=null && id2!=null)
{
return id2.compareTo(id1);
}
else
{
Date d1 = ent1.getCreatedDate();
Date d2 = ent2.getCreatedDate();
return d2.compareTo(d1);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With