What is the better way to use Optional in conditions?

Viewed 817

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

1 Answers

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"));
}
Related