问题
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;
}
}
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.
Please help.
回答1:
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());
}
回答2:
You need to wait for completion before you can do further calculation.
So, instead of your last System.out.println
, do something along
// wait and process individual values
int result = 0;
for (var f : ans) {
result += f.get();
}
System.out.println(result);
来源:https://stackoverflow.com/questions/63805486/how-to-perform-the-transformation-on-completablefuture-tasks