Remove embedded null check with 'Optional' in Java 8

  • A+

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?


You don't need the null check - .filter(p -> p.getCountry() != null). Remove this and your code should work fine. returns an Optional instance itself. So no need to apply the null check.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: