![](/img/trans.png)
[英]What is the difference between thenApply and thenApplyAsync of Java CompletableFuture?
[英]Difference between thenAccept and thenApply
我正在阅读CompletableFuture
上的文档, thenAccept()
的描述是
返回一个新的 CompletionStage,当此阶段正常完成时,将使用此阶段的结果作为所提供操作的参数来执行。
对于thenApply()
是
返回一个新的 CompletionStage,当这个阶段正常完成时,将这个阶段的结果作为提供函数的参数执行。```
谁能用一些简单的例子来解释两者之间的区别?
您需要查看完整的方法签名:
CompletableFuture<Void> thenAccept(Consumer<? super T> action)
<U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
thenAccept
接受一个Consumer
并返回一个T=Void
CF,即一个不携带值,只有完成状态的值。
另一方面, thenApply
接受一个Function
并返回一个携带函数返回值的 CF。
thenApply
返回当前阶段的结果,而thenAccept
不返回。
阅读这篇文章: http : //codeflex.co/java-multithreading-completablefuture-explained/
正如the8472清楚地解释的那样,它们通过输出值和参数来区分,因此你可以用它们做什么
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
Apply函数应用另一个函数并传递一个持有值的未来
Accept函数消耗这个值并返回未来的持有无效
我会以我记得两者之间的区别的方式来回答这个问题:考虑以下未来。
CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "Hello");
ThenAccept
基本上接受一个消费者并将计算的结果传递给它CompletableFuture<Void>
CompletableFuture<Void> future = completableFuture
.thenAccept(s -> System.out.println("Computation returned: " + s));
您可以将其与streams
forEach
相关联以便于记忆。
当thenApply
接受一个Function
实例时,使用它来处理结果并返回一个包含函数返回值的 Future :
CompletableFuture<String> future = completableFuture
.thenApply(s -> s + " World");
您可以将其与streams
map
相关联,因为它实际上正在执行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.