3

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?

1
  • Change method getValidFrom() so that rather than returning null, it returns a OffsetDateTime. If you want nulls to be low, then return a minimum value. Commented Apr 9, 2021 at 12:32

1 Answer 1

4

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())
    );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.