简体   繁体   English

链接 CompletableFuture 的 stream 还是链接 CompletableFuture?

[英]Chaining stream of CompletableFuture or chaining CompletableFuture?

I don't see a major difference between this:我没有看到这之间的主要区别:

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());

And this:和这个:

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());

I have made a test and the result and the execution time is the same.我做了一个测试,结果和执行时间是一样的。 The only difference I can see is that the second proposal allows the access to the input variable along the chain.我能看到的唯一区别是第二个提议允许沿链访问input变量。 So if I need it later in another task I can using it.因此,如果我稍后在另一项任务中需要它,我可以使用它。

Am I wrong?我错了吗? Are there other differences?还有其他区别吗?

Your conclusion is correct.你的结论是正确的。 There is (almost) no difference – calling map multiple times might allocate a bit more memory, because a new stream instance needs to be created and returned. (几乎)没有区别——多次调用map可能会分配更多的 memory,因为需要创建并返回一个新的 stream 实例。 Semantically, both forms are equivalent and produce the same result.从语义上讲,forms 是等价的并且产生相同的结果。

If you need access to the initial value of your input, then you need to combine the operations into a single operation;如果您需要访问输入的初始值,那么您需要将这些操作组合成一个操作; otherwise the variable is not available in the operation's (ie lambda) scope.否则该变量在操作(即 lambda)scope 中不可用。

More generally:更普遍:

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();

Or with method calls:或者使用方法调用:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM