Java Comparator with null fields

Viewed 4940

I have a list of entities Entity with the fields id and createdDate. I want to sort them as following:

  • higher id first
  • if id null, most recent createdDate first

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?

4 Answers

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);
     }
   }
});

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();

I don't use lambdas much but I can help you with the comparator.

Comparator<Entity> cmp = new Comparator<Entity>() {

        @Override
        public int compare(Entity e1, Entity e2) {
            if(e1.id!=null && e2.id!=null){
                return e2.id - e1.id;
            }
            return e1.createdDate - e2.createdDate;
            //createdDate should be an Integer field otherwise convert it to integer somehow.
        }

    };
    //To use this comparator
    Collections.sort(your_list,cmp);
Related