如何对CompletableFuture任务执行转换 [英] How to perform the transformation on CompletableFuture tasks
本文介绍了如何对CompletableFuture任务执行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对CompletableFuture任务列表进行一些转换,但是由于缺乏经验而遇到了一些问题.我有一个CompletableFuture列表,但是我无法对其进行进一步的转换.
I am trying to perform some transformation on the list of CompletableFuture tasks, but facing some issue because of lack of experience. I have a list of CompletableFuture but I am failing to perform further transformation on it.
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class thenapply {
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Integer> list = Arrays.asList(5, 9, 14);
final int sum = 0;
List<CompletableFuture<Integer>> ans = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
final int finali = i;
ans.add(CompletableFuture.supplyAsync(() -> square(list.get(finali))));
}
System.out.println(ans.stream()
.mapToInt(Integer::intValue).sum());
}
private static int square(int a) {
return a * a;
}
}
我知道.mapToInt(Integer::intValue)
是错误的,但是不知道如何纠正它.此外,我读到我们应该使用allOf
,但是我不确定如何在这里实现它.
I know .mapToInt(Integer::intValue)
is wrong but do not know how to correct it. Further, I am reading that we should use allOf
but I am not sure how to implement it here.
请帮助.
推荐答案
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Integer> list = Arrays.asList(5, 9, 14);
final AtomicInteger sum = new AtomicInteger(0);
int size = list.size();
CountDownLatch latch = new CountDownLatch(size);
for (int i = 0; i < size; i++) {
final int finali = i;
CompletableFuture.runAsync(() -> {
int sq= square(list.get(finali));
sum.addAndGet(sq);
latch.countDown();
});
}
latch.await();
System.out.println(sum.get());
}
这篇关于如何对CompletableFuture任务执行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文