Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove embedded null check with 'Optional' in Java 8

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?

like image 733
DilTeam Avatar asked Jul 19 '18 16:07

DilTeam


People also ask

How do you replace an Optional null check in Java 8?

With Java 8 Optional : UserObj userObj=new UserObj(); Optional. ofNullable(fetchDetails()). ifPresent(var -> userObj.

How do I stop null check in Java 8?

Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.

How do you handle Optional null?

You can create an optional object from a nullable value using the static factoy method Optional. ofNullable . The advantage over using this method is if the given value is null then it returns an empty optional and rest of the operations performed on it will be supressed. Optional<Job> optJob = Optional.

How do you handle null values in Java 8?

With the release of Java 8, a straight-forward way of handling null references was provided in the form of a new class: java. util. Optional<T> . It's a thin wrapper around other objects, so you can interact fluently with the Optional instead of a null reference directly if the contained object is not present.


1 Answers

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.

like image 67
Pankaj Singhal Avatar answered Sep 23 '22 11:09

Pankaj Singhal