Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the better way to use Optional in conditions?

Tags:

java

java-8

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

like image 654
Kishore Chandran Avatar asked Jun 20 '19 08:06

Kishore Chandran


People also ask

How to check if there is a value in an optional?

When we have an Optional object returned from a method or created by us, we can check if there is a value in it or not with the isPresent () method: This method returns true if the wrapped value is not null. Also, as of Java 11, we can do the opposite with the isEmpty method:

Can you use optional in a class?

As discussed above, Optional is meant to be used as a return type. Trying to use it as a field type is not recommended. Additionally, using Optional in a serializable class will result in a NotSerializableException. Our article Java Optional as Return Type further addresses the issues with serialization.

What are the advantages of using optional in C++?

It can help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible to the developer.

Is it OK to pass optional values to methods?

Optional s are not supposed to be passed into methods, they are only for returning optional values. Your code is perfectly fine as it is right now (might want to add a @Nullable annotation)


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"));
}
like image 193
Eran Avatar answered Sep 28 '22 05:09

Eran