So i want to do a null safe check on a value contained within a value.
So I have 3 objects contained within each other:
Person has a clothes object which has a country object which has a capital
So a person may not have clothes so a check like this throws a null pointer:
if (person.getClothes.getCountry.getCapital)
How would I make a statement like this just return false if any of the objects on the path are null?
I also don't want to do it this way. (A one-liner in Java-8 if possible.
if (person !=null) {
if (person.getClothes != null) {
if (person.getClothes.getCountry !=null) {
etc....
}
}
}
Using … != null still is the way to do it in Java 8 and even Java 11.
In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.
Void safety (also known as null safety) is a guarantee within an object-oriented programming language that no object references will have null or void values. In object-oriented languages, access to objects is achieved through references (or, equivalently, pointers).
Let's learn how to use Java 8's Optionals to make your null checks simple and less error-prone! Join the DZone community and get the full member experience. The method orElse() is invoked with the condition "If X is null, populate X. Return X.", so that the default value can be set if the optional value is not present.
You can chain all of those calls via Optional::map
. I sort of find this easier to read than if/else
, but it might be just me
Optional.ofNullable(person.getClothes())
.map(Clothes::getCountry)
.map(Country::getCapital)
.ifPresent(...)
These "cascade" null-checks are really paranoid and defensive programming. I'd start with a question, isn't better to make it fail fast or validate the input right before it's store into such a data structure?
Now to the question. As you have used nested the null-check, you can do the similar with Optional<T>
and a method Optional::map
which allows you to get a better control:
Optional.ofNullable(person.getClothes())
.map(clothes -> clothes.getCountry())
.map(country -> country.getCapital())
.orElse(..) // or throw an exception.. or use ifPresent(...)
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