将列表列表拆分为单个列表java

s6fujrry  于 2021-08-20  发布在  Java
关注(0)|答案(4)|浏览(327)

我有一个java方法,它返回以下输出:

List<CompletableFuture<List<String>>> futureResponselist;

如何从这些数据构建一个列表?因为我必须迭代最终的输出,并使用其中的“string”参数执行一些操作。
我希望这些列表中的所有字符串值都出现在最终的单个列表中。
它应该是: List<String> 我的futureresponselist大小是3。因此,到list的转换应该以非阻塞方式进行

bwitn5fc

bwitn5fc1#

你有很多方法可以做到这一点。要展平Java8及更高版本的嵌套列表,可以使用下面这样的结构在功能上实现。如果要并行处理,可以使用 Collection::parallelStream 而不是 Collection::stream .

List<String> onlyStringValues = futureResponseList.stream()
                                            .map(CompletableFuture::join)
                                            .flatMap(Collection::stream)
                                            .collect(Collectors.toList());
siotufzp

siotufzp2#

您可以使用此代码,如果列表的顺序不重要,请考虑并行化。

List<CompletableFuture<List<String>>> futureResponselist = new ArrayList<>();
futureResponselist.add(CompletableFuture.supplyAsync(() -> List.of("1" , "2")));
futureResponselist.add(CompletableFuture.supplyAsync(() -> List.of("3" , "4", "5")));
futureResponselist.add(CompletableFuture.supplyAsync(() -> List.of("6")));
List<String> result = futureResponselist
        .stream()
        .map(CompletableFuture::join)
        .flatMap(List::stream)
        .collect(Collectors.toList());

更新:更通用的方法是从 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

kx7yvsdv

kx7yvsdv3#

实际上很简单:迭代外部 list 使用增强的 for 循环,从 CompletableFuture 并将所有元素添加到结果列表中。

List<CompletableFuture<List<String>>> futureResponselist = ...

List<String> result = new ArrayList<>();
for (CompletableFuture<List<String>> future : futureResponselist)
    result.addAll(future.get());
xcitsw88

xcitsw884#

迭代futureresponselist,然后迭代每个completablefuture的字符串列表,并将该字符串添加到在这两个for循环之外声明的列表中

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();
    }
}

相关问题