Java Comparator with null fields
Using nonNull method from Object class, perhaps could solve it.
Comparator comp = Comparator
.nullsFirst(Comparator.comparing(e -> nonNull(((Entity) e).getId()))
.thenComparing(e -> ((Entity e).getCreatedDate())
.reversed();
entities.stream().filter(comp).findFirst();
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);
}
}
});
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
.