15

I replaced the following code:

if (status.getPlace() == null) {
    row.set("CountryCode", "Unknown");
    row.set("Country", "Unknown");
} else {
    if (status.getPlace().getCountryCode() == null) {
        row.set("CountryCode", "Unknown");
    } else {
        row.set("CountryCode", status.getPlace().getCountryCode());
    }
    if (status.getPlace().getCountry() == null) {
        row.set("Country", "Unknown");
    } else {
        row.set("Country", status.getPlace().getCountry());
    }
}

With this:

String countryCode = Optional.ofNullable(status.getPlace())
        .filter(p -> p.getCountryCode() != null)
        .map(Place::getCountryCode)
        .orElse("Unknown");
row.set("CountryCode", countryCode);

String country = Optional.ofNullable(status.getPlace())
        .filter(p -> p.getCountry() != null)
        .map(Place::getCountry)
        .orElse("Unknown");
row.set("Country", country);

It's working as expected but somehow I think I can do better. I still have a 'null' check in there.

.filter(p -> p.getCountryCode() != null)

Is there a way to avoid the above null check?

1
  • 3
    There is a way if you make getCountryCode return Optional, then you can simply use flatMap Commented Jul 19, 2018 at 16:25

2 Answers 2

18

You don't need the null check - .filter(p -> p.getCountry() != null). Remove this and your code should work fine.

Optional.map() returns an Optional instance itself. So no need to apply the null check.

Sign up to request clarification or add additional context in comments.

1 Comment

Don’t know who downvoted, but perhaps it’s worth to link to the specification and citing the relevant sentence: “If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.”. Maybe that’ll convince the disbelievers.
9

You don’t need the filter operation at all. if the call to Place::getCountryCode or Place::getCountry returns null then an empty optional is returned which means the orElse method will be called to retrieve the alternative value.

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.