Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I map Optional to another Optional if not present? [duplicate]

I have this Java 8 code:

public Optional<User> getUser(String id) {
    Optional<User> userFromCache = cache.getUser(id);
    if (userFromCache.isPresent()) {
        return userFromCache;
    }
    return repository.getUser(id);
}

It works fine but I'm wondering how can I chain the call to not to use if. I have tried with orElseGet but it doesn't allow to return another Optional<User> but a User.

I want something like this:

Optional<User> userFromCache = cache.getUser(id)
    .orElseGet(() -> repository.getUser(id));
like image 404
Héctor Avatar asked Dec 17 '18 14:12

Héctor


People also ask

What does Optional get return if empty?

The empty method of the Optional method is used to get the empty instance of the Optional class. The returned object doesn't have any value.

What is orElse in optional Java?

The orElse() method will return the value present in an Optional object. If the value is not present, then the passed argument is returned.

How do you add value to optional?

You can create an Optional object using the of() method, which will return an Optional object containing the given value if the value is non-null, or an empty Optional object if the value is null.


3 Answers

Since Java 9, there is Optional.or. It accepts a supplier for another Optional.

return cache.getUser(id).or(() -> repository.getUser(id));
like image 117
khelwood Avatar answered Oct 18 '22 20:10

khelwood


You can create an optional based on a nullable value from other optionals:

public Optional<User> getUser(String id) {
    return Optional.ofNullable(
        cache.getUser(id).orElseGet(
            () -> repository.getUser(id).orElse(null)
        )
    );
}

But your current solution is clearly more readable.

like image 39
ernest_k Avatar answered Oct 18 '22 21:10

ernest_k


You can still use ?:

return (userFromCache.isPresent()) ? userFromCache : repository.getUser(id);

It's obviously an if in disguise but so is any other solution.

like image 2
Erwin Smout Avatar answered Oct 18 '22 21:10

Erwin Smout