list.stream转数组
时间: 2024-05-31 16:06:06 浏览: 15
将List转换为数组可以使用stream的toArray方法。toArray方法有两种重载形式,一种是无参数的,一种是带一个IntFunction参数的。无参数的toArray方法将返回一个Object类型的数组,带参数的toArray方法可以指定返回的数组类型。
以下是使用stream将List转换为数组的示例代码:
```
List<String> list = Arrays.asList("a", "b", "c");
String[] arr1 = list.stream().toArray(String[]::new); // 指定返回的数组类型
Object[] arr2 = list.stream().toArray(); // 不指定返回的数组类型,默认返回Object类型的数组
```
相关问题
.stream().map转数组
要将.stream().map转化为数组,可以使用.collect(Collectors.toList())方法将流转化为列表,然后再使用.toArray()方法将列表转化为数组。
相关问题:
1. .stream().map如何使用?
2. .stream().collect(Collectors.
list.tostring后转数组
可以使用Java 8的Stream API将List转换为数组。具体实现方法如下:
```java
String[] strArray = list.stream().toArray(String[]::new);
```
其中,`String[]::new`表示将Stream中的元素转换为String类型的数组。
另外,如果需要将List转换为字符串后再转换为数组,可以使用以下代码:
```java
String[] strArray = list.toString().replaceAll("[\\[\\]]", "").split(", ");
```
其中,`replaceAll("[\\[\\]]", "")`表示将List转换为字符串后去掉方括号,`split(", ")`表示将字符串按照逗号和空格分割成数组。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)