When I have a number of expressions that can throw an exception, for example:
instanceObj.final_doc_type = instance.getFinalDocument().getValue().getType().getVa
Use Optional.map:
instanceObj.final_doc_type =
Optional.ofNullable(instance)
.map(Instance::getFinalDocument)
.map(Document::getValue)
.map(Value::getType)
.map(Type::getValue)
.orElse(null);
This sets final_doc_type
to null
if anything in the chain is null
.
If you only want to set its value in the case of a non-null value, remove the assignment, and change the orElse
to ifPresent
:
Optional.ofNullable(instance)
/* ... */
.ifPresent(t -> instanceObj.final_doc_type = t);