How do I deal with null and duplicate values in a Java 8 Comparator?

ace :

I have a Photo object:

public class Photo {
    @Id
    private String id;
    private LocalDateTime created;
    private Integer poNumber;
}

poNumber can be null for some photos or all photos in a set. I want to sort a set of photos according to poNumber, so that the lowest poNumber appears first in the sorted set. poNumber may also be duplicated in the set. If poNumber is duplicated then sort according to created (earliest created photo appears first). If poNumber is null then sort according to created.

I tried the below code:

Set<Photo> orderedPhotos = new TreeSet<>(
    Comparator.nullsFirst(Comparator.comparing(Photo::getPoNumber))
              .thenComparing(Photo::getCreated));

for (Photo photo : unOrderedPhotos) {
    orderedPhotos.add(photo);
}

But it throws a NullPointerException whenever poNumber is null. If poNumber is not null then it works fine. How can I solve this issue?

Oleksandr Pyrohov :

You can use a two-argument Comparator.comparing overload, for example:

import static java.util.Comparator.*; // for the sake of brevity

Set<Photo> orderedPhotos = new TreeSet<>(
    Comparator.comparing(Photo::getPoNumber, nullsFirst(naturalOrder()))
              .thenComparing(Photo::getCreated));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35980&siteId=1