Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 链接CompletableFuture的流还是链接CompletableFuture?_Java_Completable Future - Fatal编程技术网

Java 链接CompletableFuture的流还是链接CompletableFuture?

Java 链接CompletableFuture的流还是链接CompletableFuture?,java,completable-future,Java,Completable Future,我看不出这两者之间有什么主要区别: List<CompletableFuture<Integer>> intFutures = Stream.of(1, 2, 3, 4) .map(input -> CompletableFuture.supplyAsync(() -> computeSomethingLong(input))) .map(future -> future.thenApply(input -> input * 2))

我看不出这两者之间有什么主要区别:

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 intFutures=Stream.of(1,2,3,4)
.map(输入->CompletableFuture.SupplySync(()->computeSomethingLong(输入)))
.map(未来->未来,然后应用(输入->输入*2))
.map(future->future.thencose(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());
List intFutures=Stream.of(1,2,3,4)
.map(输入->CompletableFuture.SupplySync(()->computeSomethingLong(输入))
.然后应用(计算->计算*2)
.thencose(computed->CompletableFuture.supplyAsync(()->computeSomethingLong(computed)))
.collect(toList());
我做了一个测试,结果和执行时间是一样的。 我所能看到的唯一区别是,第二个方案允许访问链上的
输入
变量。因此,如果我以后在另一个任务中需要它,我可以使用它


我错了吗?还有其他区别吗?

你的结论是正确的。这(几乎)没有区别——多次调用
map
可能会分配更多的内存,因为需要创建并返回一个新的流实例。在语义上,两种形式是等价的,并产生相同的结果

如果需要访问输入的初始值,则需要将这些操作合并为单个操作;否则,该变量在操作的(即lambda)范围内不可用

更一般地说:

流
.map(x->operation1(x))
.map(x->operation2(x))
.map(x->operation3(x))
.toList();
//相当于:
流动
.map(x->operation3(operation2(operation1(x)))
.toList();
或使用方法调用:

流
.map(x->x.method1())
.map(x->x.method2())
.map(x->x.method3())
.toList();
//相当于:
流动
.map(x->x.method1().method2().method3())
.toList();

你是对的。