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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:33:24  来源:igfitidea点击:

Difference between thenAccept and thenApply

javaasynchronousjava-8completable-future

提问by Anqi Lu

I'm reading the document on CompletableFutureand 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)

thenAccepttakes a Consumerand returns a T=VoidCF, i.e. one that does not carry a value, only the completion state.

thenAccept接受 aConsumer并返回一个T=VoidCF,即不携带值,只有完成状态的CF。

thenApplyon the other hand takes a Functionand returns a CF carrying the return value of the function.

thenApply另一方面,接受 aFunction并返回一个携带函数返回值的 CF。

回答by ybonda

thenApplyreturns result of curent stage whereas thenAcceptdoes not.

thenApply返回当前阶段的结果,而thenAccept不会。

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

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

CompletableFuture methods

CompletableFuture 方法

回答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

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