Skip to content
Advertisement

Sorting multiple conditions with null value

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?

Advertisement

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())
    );
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement