使用流API将arraylist添加到arraylist

问题描述 投票:1回答:1

有一个生成ArrayList的方法:

List<Entity> method (String s){
    ........
    return list;
} 

如何使用流API从List集合中收集List? (类似于newList.addAll(list);

List<String> stringList = someGenerateStrings();

List<Entity> newList = stringList.stream()
    .map(this::method)
    .collect(?)
java collections stream
1个回答
0
投票

首先,您需要将列表流展平为列表元素流。你可以使用Stream's flatMap method

返回一个流,该流包含将此流的每个元素替换为通过将提供的映射函数应用于每个元素而生成的映射流的内容的结果。

这基本上将你创造的内部Streams中的元素带入主要的Stream

.flatMap(p -> method(p).stream())

然后它就像收集到List一样简单。

.collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.