美文网首页
thenApply与thenCompose的异同

thenApply与thenCompose的异同

作者: 竹鼠不要中暑 | 来源:发表于2019-03-11 16:26 被阅读0次

    thenApplythenCompose都是对一个CompletableFuture返回的结果进行后续操作,返回一个新的CompletableFuture。

    不同

    先来看看两个方法的声明描述:

    <U> CompletionStage<U> thenApply​(Function<? super T,? extends U> fn)
    
    <U> CompletionStage<U> thenCompose​(Function<? super T,? extends CompletionStage<U>> fn)
    

    可以看到,两个方法的返回值都是CompletionStage<U>,不同之处在于它们的传入参数fn.

    • 对于thenApplyfn函数是一个对一个已完成的stage或者说CompletableFuture的的返回值进行计算、操作;
    • 对于thenComposefn函数是对另一个CompletableFuture进行计算、操作。

    例子:

            CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> 100).thenApply(num -> num + " to String");
            CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> 100).thenCompose(num -> CompletableFuture.supplyAsync(() -> num + " to String"));
    
            System.out.println(f1.join()); // 100 to String
            System.out.println(f2.join()); // 100 to String
    

    例子中,thApplythenCompose都是将一个CompletableFuture<Integer>转换为CompletableFuture<String>。不同的是,thenApply中的传入函数的返回值是String,而thenCompose的传入函数的返回值是CompletableFuture<String>。就好像stream中学到的mapflatMap。回想我们做过的二维数组转一维数组,使用stream().flatMap映射时,我们是把流中的每个数据(数组)又展开为了流。

    相关文章

      网友评论

          本文标题:thenApply与thenCompose的异同

          本文链接:https://www.haomeiwen.com/subject/thdbpqtx.html