List<CompletableFuture<List>> futureResult = futureResponselist .stream() .map(future -> future.thenApply(Function.identity())) // do some processing with list here we just return it but you can do something else .map(future -> future.thenApply(Function.identity())) .collect(Collectors.toList()); futureResult .parallelStream() .map(CompletableFuture::join) .flatMap(List::stream) .forEach(System.out::println); // do something when the result is ready here we just print it
实际上很简单:迭代外部 list 使用增强的 for 循环,从 CompletableFuture 并将所有元素添加到结果列表中。
List<CompletableFuture<List<String>>> futureResponselist = ...
List<String> result = new ArrayList<>();
for (CompletableFuture<List<String>> future : futureResponselist)
result.addAll(future.get());
List<CompletableFuture<List<String>>> futureResponselist;
// List of string to store combined result
List<String> mergedList = new ArrayList<>();
for (CompletableFuture com : futureResponselist) {
for (String string : com.getYourListOfString()) {
mergedList.add();
}
}
4条答案
按热度按时间bwitn5fc1#
你有很多方法可以做到这一点。要展平Java8及更高版本的嵌套列表,可以使用下面这样的结构在功能上实现。如果要并行处理,可以使用
Collection::parallelStream
而不是Collection::stream
.siotufzp2#
您可以使用此代码,如果列表的顺序不重要,请考虑并行化。
更新:更通用的方法是从
Modern Java in Action
```Executor executor =
Executors.newFixedThreadPool(5);
List<CompletableFuture<List>> futureResponselist = new ArrayList<>();
futureResponselist.add(CompletableFuture.supplyAsync(() -> List.of("1" , "2"), executor));
futureResponselist.add(CompletableFuture.supplyAsync(() -> List.of("3" , "4", "5"), executor));
futureResponselist.add(CompletableFuture.supplyAsync(() -> List.of("6"), executor));
List<CompletableFuture<List>> futureResult = futureResponselist
.stream()
.map(future -> future.thenApply(Function.identity())) // do some processing with list here we just return it but you can do something else
.map(future -> future.thenApply(Function.identity()))
.collect(Collectors.toList());
futureResult
.parallelStream()
.map(CompletableFuture::join)
.flatMap(List::stream)
.forEach(System.out::println); // do something when the result is ready here we just print it
kx7yvsdv3#
实际上很简单:迭代外部
list
使用增强的for
循环,从CompletableFuture
并将所有元素添加到结果列表中。xcitsw884#
迭代futureresponselist,然后迭代每个completablefuture的字符串列表,并将该字符串添加到在这两个for循环之外声明的列表中