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?
With Java 8 Optional : UserObj userObj=new UserObj(); Optional. ofNullable(fetchDetails()). ifPresent(var -> userObj.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With