Difference between thenAccept and thenApply

Anqi Lu picture Anqi Lu · Jul 18, 2017 · Viewed 18.3k times · Source

I'm reading the document on CompletableFuture and The description for thenAccept() is

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied action.

and for thenApply() is

Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied function.```

Can anyone explain the difference between the two with some simple examples?

Answer

the8472 picture the8472 · Jul 18, 2017

You need to look at the full method signatures:

CompletableFuture<Void>     thenAccept(Consumer<? super T> action)
<U> CompletableFuture<U>    thenApply(Function<? super T,? extends U> fn)

thenAccept takes a Consumer and returns a T=Void CF, i.e. one that does not carry a value, only the completion state.

thenApply on the other hand takes a Function and returns a CF carrying the return value of the function.