steam流将List<List<String>>展开为List<String>
时间: 2023-11-11 08:45:09 浏览: 63
您可以使用Java 8的流(Stream)来将List<List<String>>展开为List<String>。下面是一个示例代码:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<List<String>> nestedList = new ArrayList<>();
nestedList.add(List.of("1", "2", "3"));
nestedList.add(List.of("4", "5"));
nestedList.add(List.of("6", "7", "8", "9"));
List<String> flattenedList = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flattenedList);
}
}
```
在这个示例中,我们首先创建了一个包含多个内部列表的外部列表(nestedList)。然后,我们使用`stream()`方法将外部列表转换成流。接下来,我们使用`flatMap()`方法将内部列表的流展开为单个流。最后,我们使用`collect()`方法将展开后的元素收集到一个新的列表中(flattenedList)。
运行这个示例代码,将打印出展开后的列表:
```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
```
这样就成功将List<List<String>>展开为了List<String>。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)