What is the better way to use Optional in conditions?

Kishore Chandran :

I have already written the code, but the thing is I feel there could be better way to write the below code,

This must be possible only from Java 8

private User getUser(String userId) {
    Optional<User> optionalUser = userDAO.getUserById(userId);
    if(optionalUser.isPresent())
        return optionalUser.get();
    throw new UserDefinedException("User not present");
}

I expect to write the above in one line

Eran :

You can use orElseThrow, which will return the value if present or throw the specified exception if not:

private User getUser(String userId) {
    return userDAO.getUserById(userId)
                  .orElseThrow(() -> new UserDefinedException("User not present"));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=120622&siteId=1