Sorting multiple conditions with null value

Tags: ,



I have this code, which sorts an array list based on 3 variables

        result.sort(Comparator.comparing(FeConsumptionChannelDTO::getMeterName)
                .thenComparing(FeConsumptionChannelDTO::getValueTypeSeq)
                .thenComparing(Comparator.comparing(FeConsumptionChannelDTO::getValidFrom).reversed())
        );

But the last variable, getValidFrom can be null since it is OffsetDateTime. If it is null, it throws a NullPointerException. Is there a way to handle null values sorting this way? Or I have to create my own comparing method?

Answer

Use the nullsFirst() (null < non-null) or nullsLast() to account for nullability:

result.sort(Comparator.comparing(FeConsumptionChannelDTO::getMeterName)
            .thenComparing(FeConsumptionChannelDTO::getValueTypeSeq)
            .thenComparing(Comparator.nullsFirst(Comparator.comparing(FeConsumptionChannelDTO::getValidFrom)).reversed())
    );


Source: stackoverflow