相关疑难解决方法(0)

CompletableFuture | 然后应用vs thenCompose

我无法理解thenApply(和之间的区别thenCompose().

那么,有人可以提供有效的用例吗?

来自Java文档:

thenApply(Function<? super T,? extends U> fn)
Run Code Online (Sandbox Code Playgroud)

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

thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
Run Code Online (Sandbox Code Playgroud)

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

我得到的第二个参数thenCompose扩展了CompletionStage,thenApply而不是.

有人可以提供一个例子,我必须使用thenApply何时使用thenCompose

java java-8 completable-future

91
推荐指数
5
解决办法
4万
查看次数

Difference between Java8 thenCompose and thenComposeAsync

Given this piece of code:

public List<String> findPrices(String product){
    List<CompletableFuture<String>> priceFutures =
    shops.stream()
         .map(shop -> CompletableFuture.supplyAsync(
                () -> shop.getPrice(product), executor))
         .map(future -> future.thenApply(Quote::parse))
         .map(future -> future.thenCompose(quote ->
                CompletableFuture.supplyAsync(
                        () -> Discount.applyDiscount(quote), executor
                )))
         .collect(toList());

    return priceFutures.stream()
                       .map(CompletableFuture::join)
                       .collect(toList());
}
Run Code Online (Sandbox Code Playgroud)

This part of it:

.map(future -> future.thenCompose(quote ->
                CompletableFuture.supplyAsync(
                        () -> Discount.applyDiscount(quote), executor
                )))
Run Code Online (Sandbox Code Playgroud)

Could it be rewrite as:

.map(future -> 
    future.thenComposeAsync(quote -> Discount.applyDiscount(quote), executor))
Run Code Online (Sandbox Code Playgroud)

I took this code from an example of a book and says the two solutions are …

java java-8 completable-future

8
推荐指数
1
解决办法
3883
查看次数

标签 统计

completable-future ×2

java ×2

java-8 ×2