简体   繁体   中英

Difference between thenAccept and thenApply

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?

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, ie 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.

thenApply returns result of curent stage whereas thenAccept does not.

Read this article: http://codeflex.co/java-multithreading-completablefuture-explained/

CompletableFuture 方法

As the8472 clearly explained, they are differentiate by their output value and args and thus what you can do with them

CompletableFuture.completedFuture("FUTURE")
                    .thenApply(f -> f.toLowerCase())
                    .thenAccept(f -> System.out.println(f))
                    .thenAccept(f -> System.out.println(f))
                    .thenApply(f -> new String("FUTURE"))
                    .thenAccept(f -> System.out.println(f));
future
null
FUTURE

the Apply functions apply another function and pass a future holding a value

the Accept functions consume this value and returns future holding void

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM