thenApply()和thenCompose()的区别

  1. thenapply()是接受一个Function<? super T,? extends U>参数用来转换CompletableFuture,相当于流的map操作,返回的是非CompletableFuture类型,它的功能相当于将CompletableFuture<T>转换成CompletableFuture<U>。
    thenApply()源码:
 public <U> CompletableFuture<U> thenApply(
    Function<? super T,? extends U> fn) {
        return uniApplyStage(null, fn);
   }

解读:
参数: Function<? super T,? extends U> fn)
输入前面的CompletableFuture<T>中的T的值,返回一个继承U的类型的值,将这个值返回
顺序:先确定返回值U或其子类,再确定方法中 public <U> CompletableFuture<U> thenApply()中的 <U>类型

  1. thenCompose()在异步操作完成的时候对异步操作的结果进行一些操作,并且仍然返回CompletableFuture类型,相当于flatMap,用来连接两个CompletableFuture。

总结:thenApply()转换的是泛型中的类型,是同一个CompletableFuture;
thenCompose()用来连接两个CompletableFuture,是生成一个新的CompletableFuture。他们都是让CompletableFuture可以对返回的结果进行后续操作,就像流一样进行map和flatMap的装换。

  1. 例子:
    thenApply():
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
      return 100;
});
CompletableFuture<String> f = future.thenApplyAsync(i -> i * 10).thenApply(i -> i.toString());

System.out.println(f.get()); //"1000"

thenCompose():

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    return 100;
});
CompletableFuture<String> f = future.thenCompose( i -> {
    return CompletableFuture.supplyAsync(() -> {
        return (i * 10) + "";
    });
});

System.out.println(f.get()); //1000
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容