简体   繁体   中英

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?

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())
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM