[英]Chaining stream of CompletableFuture or chaining CompletableFuture?
我沒有看到這之間的主要區別:
List<CompletableFuture<Integer>> intFutures = Stream.of(1, 2, 3, 4)
.map(input -> CompletableFuture.supplyAsync(() -> computeSomethingLong(input)))
.map(future -> future.thenApply(input -> input * 2))
.map(future -> future.thenCompose(computed -> CompletableFuture.supplyAsync(() -> computeSomethingLong(computed))))
.collect(toList());
和這個:
List<CompletableFuture<Integer>> intFutures = Stream.of(1, 2, 3, 4)
.map(input -> CompletableFuture.supplyAsync(() -> computeSomethingLong(input))
.thenApply(computed -> computed * 2)
.thenCompose(computed -> CompletableFuture.supplyAsync(() -> computeSomethingLong(computed))))
.collect(toList());
我做了一個測試,結果和執行時間是一樣的。 我能看到的唯一區別是第二個提議允許沿鏈訪問input
變量。 因此,如果我稍后在另一項任務中需要它,我可以使用它。
我錯了嗎? 還有其他區別嗎?
你的結論是正確的。 (幾乎)沒有區別——多次調用map
可能會分配更多的 memory,因為需要創建並返回一個新的 stream 實例。 從語義上講,forms 是等價的並且產生相同的結果。
如果您需要訪問輸入的初始值,那么您需要將這些操作組合成一個操作; 否則該變量在操作(即 lambda)scope 中不可用。
更普遍:
stream
.map(x -> operation1(x))
.map(x -> operation2(x))
.map(x -> operation3(x))
.toList();
// is equivalent to:
stream
.map(x -> operation3(operation2(operation1(x))))
.toList();
或者使用方法調用:
stream
.map(x -> x.method1())
.map(x -> x.method2())
.map(x -> x.method3())
.toList();
// equivalent to:
stream
.map(x -> x.method1().method2().method3())
.toList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.