John Beff
John Beff

Reputation: 133

From Optional<CompletableFuture<T>> to CompletableFuture<Optional<T>>

I would like to convert Optional<CompletableFuture<T>> to CompletableFuture<Optional<T>>. Is there more idiomatic way not using Optional.get()?

Optional<CompletableFuture<T>> opt = Optional.empty();
CompletableFuture<Optional<T>> fut =
        opt.isPresent() ?
                opt.get().thenApply(Optional::of) :
                CompletableFuture.completedFuture(Optional.empty());

Upvotes: 2

Views: 4742

Answers (1)

Didier L
Didier L

Reputation: 20579

You can do the conversion with a combination of map() and orElseGet():

CompletableFuture<Optional<T>> fut = opt.map(f -> f.thenApply(Optional::of))
    // now you have an Optional<CompletableFuture<Optional<T>>>
    // just get rid of the outer Optional and you have the desired result:
    .orElseGet(() -> CompletableFuture.completedFuture(Optional.empty()))

Alternatively, you can also do the following:

opt.orElseGet(() -> CompletableFuture.completedFuture(null))
   .thenApply(Optional:‌​:ofNullable)

the main difference being that if the initial CompletableFuture returns null, this one will not throw a NullPointerException.

Upvotes: 4

Related Questions