Lorayne
Lorayne

Reputation: 33

Null safe comparator with two compares in java

I have a list with rooms. Those rooms can be in usage by a person on a specific date or planned to be used in the future without having a specific date. At first it went really well, but since we allow null values for the dates, I can't use this sorting method anymore. The most important thing is, that it should first be sorted by person and then the dates should be listed. The null values should be on the bottom of each person listing. I tried a bit with nullFirst(), but didn't manage to write an error free code :D Most examples online only have one comparing, instead of two. (The person will never be null)

roomTOs.sort(Comparator
            .comparing(
                    personTO::getPersonName)
            .thenComparing(
                    personTO::getUsedDate));

Upvotes: 1

Views: 338

Answers (1)

Sweeper
Sweeper

Reputation: 271105

If I understood correctly, you want something like this:

roomTOs.sort(Comparator
            .comparing(
                    personTO::getPersonName)
            .thenComparing(
                    personTO::getUsedDate, Comparator.nullsLast(Comparator.naturalOrder()))
            );

Upvotes: 2

Related Questions