I have a list of entities Entity with the fields id and createdDate. I want to sort them as following:
- higher
idfirst - if
idnull, most recentcreatedDatefirst
I'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?