object.getProperty().getSubProperty().getSubSubProperty();
Consider the code above. An object has a property, that has a subProperty, that has a subSubProperty, that can be accessed with getter methods.
What can we do in Java to achieve something like:
Util.coalesce(object.getProperty().getSubProperty().getSubSubProperty(), defaultSubSubProperty);
org.apache.commons.lang3.ObjectUtils.defaultIfNull
has something like this. But the problem with this method is that it just works when property and subProperty are not null. I would like a way to get subSubProperty or defaultSubSubProperty even when property and subProperty are null.
How can we do this?
You can use Optional in Java 8.
String s = Optional.ofNullable(object)
.map(Type::getProperty)
.map(Type2::getSubProperty)
.map(Type3::getSubSubProperty)
.orElse(defaultValue);
You can also use orElseGet(Supplier)
or orElseThrow(Throwable)
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