thenApply()和thenCompose()的异同
相同之处
thenApply()
和themCompose()
都是用于连接多个CompletableFuture
调用,通过类似于流的操作来处理CompletableFutrue
的结果
不同之处
-
thenApply()
接收一个函数作为参数,使用该函数处理上一个CompletableFuture
调用的结果,并返回一个具有处理结果的Future
对象CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenApply(string -> string + " world"); try { System.out.println(completableFuture.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); }
可以看到
thenApply()
适用于对CompletableFuture
调用的结果进行一些转换。 -
thenCompose()
的参数为一个返回CompletableFuture
实例的函数,该函数的参数是先前计算步骤的结果CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello").thenCompose(string -> CompletableFuture.supplyAsync(() -> string + " world")); try { System.out.println(completableFuture.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); }
可以看到
thenCompose()
会将内部的CompletableFuture
调用展开来并使用上一个CompletableFutre
调用的结果在下一步的CompletableFuture
调用中进行运算,因此thenCompose()
更适用于多个CompletableFuture
调用的连接。
参考
网友评论