如何在java中处理带有CompletableFuture的List列表?

时间:2017-03-02 13:29:37

标签: java multithreading java-8 java-stream completable-future

我在java中有一个List<List<String>>,我希望使用固定线程池实例3异步处理父列表中的List List。我试图在java 8中使用CompletableFuture和Stream。我不明白如何合并这些二,如何进行。 PFB Code我到目前为止已尝试过。在处理器中我只是打印它,但我会进行数据库操作。

所以在这里我尝试流List<List<String>>并根据List大小创建线程数,但是将Streaming List作为参数传递给带有CompletableFuture的处理器。

public class CompletableFutureWithList {
    public static void main(String args[]) {
        List<List<String>> aList = new ArrayList<>();
        aList.add(new ArrayList<>(Arrays.asList("xyz", "abc")));
        aList.add(new ArrayList<>(Arrays.asList("qwe", "poi")));
        System.out.println("helo...");
        ExecutorService executor = Executors.newFixedThreadPool(aList.size());
        //aList.stream().flatMap(List::stream).
        Processor aProcessor = new Processor();
        List<String> tempList = new ArrayList<>();
        CompletableFuture aComFuture = supplyAsync(() -> aProcessor.processList(tempList), executor);
        try {
            aComFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
public class Processor {
    public boolean processList(List<String> tempList) {
        for (String string : tempList) {
            System.out.println("Output: " + string);
        }
        return true;
    }
}  

2 个答案:

答案 0 :(得分:1)

根据我的理解,您需要为List<String>

中的每个List<List<String>>调用处理器

所以你可以做的是使用CompletableFuture创建所有新线程然后等待它们全部完成并对返回值进行任何处理。

所以你能做的就是这样的事情

List<List<String>> aList = new ArrayList<>();

//Create all CFs
List<CompletableFuture<Boolean>> futureList = aList.stream()
            .map(strings -> CompletableFuture.supplyAsync(() -> processList(strings), executor))
            .collect(toList());

//Wait for them all to complete
CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).join();

//Do processing of the results
Stream<Boolean> booleanStream = futureList.stream()
            .map(CompletableFuture::join);
//Do other stuff you need

答案 1 :(得分:0)

这是你如何合并list和completablefuture的列表。

public static void main(String args[]) {
    List<List<String>> aList = new ArrayList<>();
    aList.add(new ArrayList<>(Arrays.asList("xyz", "abc")));
    aList.add(new ArrayList<>(Arrays.asList("qwe", "poi")));
    System.out.println("hello...");

    Processor aProcessor = new Processor();
    List<String> tempList = new ArrayList<>();
    CompletableFuture aComFuture = CompletableFuture.supplyAsync(() -> "");

    aList.stream()
            .forEach(list -> aComFuture.thenApply(fn -> aProcessor.processList(list)));

    aComFuture.join();
}

static class Processor {
    public boolean processList(List<String> tempList) {
        for (String string : tempList) {
            System.out.println("Output: " + string);
        }
        return true;
    }
}