How to perform the transformation on CompletableFuture tasks

烂漫一生 提交于 2021-02-08 06:53:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!