Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient null check in Java 11 [duplicate]

I need to use a getter which is 3 levels down in the object.

response.getServiceError().getErrorCode()

It is possible one or more objects could be NULL. Now, I am doing this

if (response != null && response.getServiceError() != null && response.getServiceError().getErrorCode() != null && response.getServiceError().getErrorCode().equals("errCode123")) {
     //doSomething;
}

Is there a better and/or elegant way to construct that if condition?

like image 656
Trozan Avatar asked Mar 03 '23 01:03

Trozan


1 Answers

Use Optional!

Optional.ofNullable(response)
    .map(Response::getServiceError)
    .map(ServiceError::getErrorCode)
    .filter(code -> code.equals("errCode123"))
    .ifPresent(code -> {
        // doSomething
    });

like image 127
JDrost1818 Avatar answered Mar 13 '23 04:03

JDrost1818