简体   繁体   中英

get default value if the object is null in Java

I am curius to know how I can write a shorter version of the following code in Java.

I have the following Java class (belongs to JAX-RS):

I need back the int value of the responseStatus if that possible (response is not null) otherwise default int status value needs to be returned.

I do not want to add any library dependency to my project just for this small piece of code.

This is the code what come up in my mind first:

private static int getDefaultStatusCodeIfNull(final Response response) {
    if (Objects.isNull(response)) {
        return Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
    }

    return response.getStatus();
}

The following code is maybe shorter with lambda but it is so long and hard to read:

int status = Optional.ofNullable(response)
      .orElse(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build()).getStatus();

Is there any shorter one line way to get this int value?

Do you think the 2nd one is better solution then the 1st?

使用三元运算符,也许吗?

return (response == null) ? Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() : response.getStatus();

您可以使用三元运算符,该运算符可以将if / else放在一行上:

int status = (response == null) ? Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() : response.getStatus();

The slightly cleaner lambda version is:

Optional.ofNullable(response).map(Response::getStatus).orElse(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())

Though honestly, I think the ternary operator here is cleaner.

I would prefer your first version, as using lanbda sounds much like overkill.

You could also use the ternary operator, as others have already pointed out:

private static int getDefaultStatusCodeIfNull(final Response response) {
    return response != null ? response.getStatus()  Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
}
int status = response==null?Response.Status.INTERNAL_SERVER_ERROR.getStatusCode():response.getStatus();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM