将string转化为list<String>
时间: 2023-11-10 10:13:02 浏览: 34
可以使用split()方法将一个字符串按照指定的分隔符分割成多个子字符串,并将这些子字符串存储到一个字符串数组中。然后,再将字符串数组转换为List<String>类型。
下面是一个示例代码:
```java
String str = "hello,world,test";
String[] strArr = str.split(",");
List<String> strList = Arrays.asList(strArr);
```
在上面的代码中,我们首先使用split()方法将字符串按照逗号分隔成三个子字符串,并将它们存储到一个字符串数组中。然后,我们使用Arrays.asList()方法将字符串数组转换为List<String>类型的列表。
相关问题
List<List<String>> 转换成List<String>
List<List<String>> 转换成 List<String> 的方法是使用flatMap函数。flatMap函数将多个列表合并为一个列表。首先,我们可以使用stream()函数将List<List<String>>转换为Stream<List<String>>。然后,我们可以使用flatMap()函数将Stream<List<String>>转换为Stream<String>,并使用collect()函数将Stream<String>转换为List<String>。以下是示例代码:
List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("A", "B", "C"));
list.add(Arrays.asList("D", "E", "F"));
list.add(Arrays.asList("G", "H", "I"));
List<String> result = list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println(result);
输出结果为:[A, B, C, D, E, F, G, H, I]
用Java将List<List<String>>转换成List<String>
在Java中,我们可以使用forEach循环和Stream API来将List<List<String>>转换为List<String>。
首先,我们可以使用forEach循环遍历List<List<String>>中的每个元素,然后将每个元素添加到一个新的List<String>中。代码示例如下:
```java
List<List<String>> nestedList = new ArrayList<>();
nestedList.add(Arrays.asList("element1", "element2"));
nestedList.add(Arrays.asList("element3", "element4"));
List<String> flatList = new ArrayList<>();
nestedList.forEach(subList -> flatList.addAll(subList));
```
另一种方法是使用Stream API的flatMap操作,它将嵌套的列表展平为一个单独的列表。代码示例如下:
```java
List<List<String>> nestedList = new ArrayList<>();
nestedList.add(Arrays.asList("element1", "element2"));
nestedList.add(Arrays.asList("element3", "element4"));
List<String> flatList = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
```
以上两种方法都可以将List<List<String>>转换为List<String>。请根据具体需求选择适合的方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>