java List<string> arr 转换为 string[] arr
时间: 2023-11-10 14:47:56 浏览: 36
可以使用 List 的 toArray 方法将 List 转换成数组:
```java
List<String> list = new ArrayList<>();
// 添加元素到列表中
String[] arr = list.toArray(new String[0]);
```
注意,如果传递给 toArray 方法的数组参数长度为零,则会返回一个新的数组,该数组的长度等于列表的大小,并且类型与列表元素的类型相同。
相关问题
LIST<string> 转换为List<实体类>
可以使用Java 8的Stream API来实现LIST<string>转换为List<实体类>。具体步骤如下:
1. 创建一个实体类,例如TempModel。
2. 使用Stream的map方法将LIST<string>中的每个元素映射为一个TempModel对象。
3. 使用Stream的collect方法将映射后的TempModel对象收集到一个List中。
代码示例:
```
List<String> stringList = Arrays.asList("1,John", "2,Jane", "3,Bob");
List<TempModel> tempModelList = stringList.stream()
.map(str -> {
String[] arr = str.split(",");
return new TempModel(Integer.parseInt(arr[0]), arr[1]);
})
.collect(Collectors.toList());
```
List<String>如何转为Map<String,List<String>>
可以使用Java 8的流(Stream)和Collectors工具类来将List<String>转换为Map<String,List<String>>。
假设现在有一个List<String>的变量名为list,其中每个元素都包含一个逗号分隔的键值对,例如"key1,value1"。
以下是将List<String>转换为Map<String,List<String>>的示例代码:
```
Map<String,List<String>> map = list.stream()
.map(str -> str.split(","))
.collect(Collectors.groupingBy(
arr -> arr[0],
Collectors.mapping(arr -> arr[1], Collectors.toList())
));
```
解释一下上面的代码:
1. 使用stream()方法将List<String>转换为Stream<String>。
2. 使用map()方法将每个String元素拆分成String数组,其中第一个元素作为键,第二个元素作为值。
3. 使用Collectors.groupingBy()方法将元素按照键分组,然后使用Collectors.mapping()方法将每个元素的值提取出来,并将其收集到List中作为值。
这样就可以得到一个Map<String,List<String>>,其中每个键对应一个List<String>,包含该键对应的所有值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)