java thenAccept 和 thenApply 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45174233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between thenAccept and thenApply
提问by Anqi Lu
I'm reading the document on CompletableFuture
and The description for thenAccept()
is
我正在阅读文档CompletableFuture
,其描述thenAccept()
是
Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied action.
返回一个新的 CompletionStage,当此阶段正常完成时,将使用此阶段的结果作为提供的操作的参数来执行。
and for thenApply()
is
因为thenApply()
是
Returns a new CompletionStage that, when this stage completes normally, is executed with this stage's result as the argument to the supplied function.```
返回一个新的 CompletionStage,当这个阶段正常完成时,将这个阶段的结果作为提供函数的参数执行。```
Can anyone explain the difference between the two with some simple examples?
谁能用一些简单的例子来解释两者之间的区别?
回答by the8472
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.
thenAccept
接受 aConsumer
并返回一个T=Void
CF,即不携带值,只有完成状态的CF。
thenApply
on the other hand takes a Function
and returns a CF carrying the return value of the function.
thenApply
另一方面,接受 aFunction
并返回一个携带函数返回值的 CF。
回答by ybonda
thenApply
returns result of curent stage whereas thenAccept
does not.
thenApply
返回当前阶段的结果,而thenAccept
不会。
Read this article: http://codeflex.co/java-multithreading-completablefuture-explained/
阅读这篇文章:http: //codeflex.co/java-multithreading-completablefuture-explained/
回答by shahaf
As the8472clearly explained, they are differentiate by their output value and args and thus what you can do with them
正如8472清楚地解释的那样,它们通过输出值和参数来区分,因此你可以用它们做什么
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 Applyfunctions apply another function and pass a future holding a value
在应用功能应用其他功能,并通过未来持有价值
the Acceptfunctions consume this value and returns future holding void
在接受功能消耗这个价值和回报的未来持无效