Java optional usage at right place

Viewed 42

I was reading about Java 8 Optional and wanted to know the correct approach of using it. Traditional way,

User user = getUser();
if (user != null) {
 //perform action
}

With Optional,

Optional<User> userOptional = getUser();
if (userOptional.isPresent()) {
    User user = userOptional.get();
    //perform action
 }

With optional it requires more lines of code. Can you tell me where it is beneficial ?

1 Answers

The situation you've described is the use case for Optional.ifPresent(), which expects a Consumer representing the action.

getUser().ifPresent(user -> *do the action*);

You very rarely need isPresent() check in practice. When you're using it in your code - pause for a second, most likely you're not leveraging the Optional API to its full power.

Related