How to encode smart coalesce in Java?

object.getProperty().getSubProperty().getSubSubProperty();

Consider the code above. An object has a property that has subProperty, which has subSubProperty, which can be accessed using 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 the property and subProperty are non-zero. I would like to get SubSubProperty or defaultSubSubProperty, even if the property and subProperty are null.

How can we do this?

+5
source share
1 answer

You can use the option 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)

+10
source

All Articles