Search code examples
javaasynchronouscompletable-future

How to check if an entity inside completablefuture is null


I am trying to understand CompletableFurue in Java and I am stuck with the following.

CompletableFuture<String> cf = getString(); 

I want to check if the String present inside the completable future is "null" or not. How can I do this without using the get() or join() function?


Solution

  • You don't, because the value may not be available yet.

    What you can do, is move the check (and follow-up logic) inside the CompletableFuture, using one of its many methods. For instance:

    CompletableFuture<Void> cf2 = cf.thenAccept(value -> {
        if (value != null) {
            // do something with the value
        }
    });