Difference between thenAccept and thenApply

Viewed 27675

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?

4 Answers

I would answer this question in the way I remember the difference between the two: Consider the following future.

CompletableFuture<String> completableFuture
  = CompletableFuture.supplyAsync(() -> "Hello");

ThenAccept basically takes a consumer and passes it the result of the computation CompletableFuture<Void>

CompletableFuture<Void> future = completableFuture
  .thenAccept(s -> System.out.println("Computation returned: " + s));

You can associate this with forEach in streams for easy remembering.

Where as thenApply accepts a Function instance, uses it to process the result and returns a Future that holds a value returned by a function:

CompletableFuture<String> future = completableFuture
  .thenApply(s -> s + " World");

You can associate this with map in the streams as it is actually performing a transformation.

Related