How to deal with null and duplicate values in Java 8 Comparator?

  • A+
Category:Languages

I have 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 set of photos according to poNumber, so that lowest poNumber appears first in the sorted set. poNumber may also be duplicate in the set. If poNumber is duplicate then sort according to created (earliest created photo appears first). If poNumber is null then sort according to created.

I tried 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 NullPointerException whenever poNumber is null. If poNumber is not null then works fine. How to solve this issue?

 


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

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: