thenAccept和thenApply之间的区别

Anq*_* Lu 25 java asynchronous java-8 completable-future

我正在阅读文档CompletableFuture和描述thenAccept()

返回一个新的CompletionStage,当此阶段正常完成时,将使用此阶段的结果作为所提供操作的参数执行.

而且thenApply()

返回一个新的CompletionStage,当这个阶段正常完成时,将执行此阶段的结果作为所提供函数的参数.``

谁能用一些简单的例子解释两者之间的区别?

the*_*472 28

您需要查看完整方法签名:

CompletableFuture<Void>     thenAccept(Consumer<? super T> action)
<U> CompletableFuture<U>    thenApply(Function<? super T,? extends U> fn)
Run Code Online (Sandbox Code Playgroud)

thenAccept取一个Consumer并返回一个T=VoidCF,即一个不带值的CF,只返回一个完成状态.

thenApply另一方面取a Function并返回带有函数返回值的CF.

  • 如果我们把它作为与Stream的比较,那么接受()是类似于forEach(消费者)和应用程序类似于map(Function)的一些东西 (4认同)

Yur*_*uri 9

thenApply返回固有阶段的结果,而thenAccept不是.

阅读这篇文章:http://codeflex.co/java-multithreading-completablefuture-explained/

CompletableFuture方法


小智 7

我会用我记得两者之间区别的方式来回答这个问题:考虑以下未来。

CompletableFuture<String> completableFuture
  = CompletableFuture.supplyAsync(() -> "Hello");
Run Code Online (Sandbox Code Playgroud)

ThenAccept基本上接受一个消费者并将计算结果传递给它CompletableFuture<Void>

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

您可以将其与forEachin关联起来streams以方便记忆。

其中 asthenApply接受一个Function实例,使用它来处理结果并返回一个 Future,其中保存函数返回的值:

CompletableFuture<String> future = completableFuture
  .thenApply(s -> s + " World");
Run Code Online (Sandbox Code Playgroud)

您可以将其与mapin关联起来streams,因为它实际上正在执行转换。


sha*_*haf 5

正如8472明确解释的那样,它们的区别在于其输出值和参数,因此您可以做什么

CompletableFuture.completedFuture("FUTURE")
                .thenApply(r -> r.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
Run Code Online (Sandbox Code Playgroud)

应用功能应用其他功能,并通过未来持有价值

接受功能消耗这个价值和回报的未来持无效