thenApply与thenCompose的异同

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映射时,我们是把流中的每个数据(数组)又展开为了流。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容