List<String> toString后 又如何转回List<String>
时间: 2023-11-11 15:51:03 浏览: 95
要将 List<String> 转回 List<List<String>> ,可以使用 Java 的循环语句和 List 的 add 方法。首先,创建一个新的空嵌套列表 nestedList。然后,遍历 List<String> 中的每个元素,将每个元素添加到一个新的内部列表 innerList 中。在遍历过程中,可以根据需要创建新的内部列表,当遇到需要新的内部列表时,将 innerList 添加到 nestedList 中,并重新创建一个新的内部列表。最后,在遍历完成后,将 innerList 添加到 nestedList 中,并返回 nestedList。
例如,假设我们有一个 List<String> 的对象 flatList,我们可以使用以下代码将其转回 List<List<String>>:
```
List<List<String>> nestedList = new ArrayList<>();
List<String> innerList = new ArrayList<>();
for (String element : flatList) {
innerList.add(element);
// 根据需要创建新的内部列表
// if (需要新的内部列表) {
// nestedList.add(innerList);
// innerList = new ArrayList<>();
// }
}
nestedList.add(innerList);
```
相关问题
list<String> tostring
抱歉,CSDN的ChatGPT AI暂时无法直接提供代码。但是,我可以帮助您理解如何将一个字符串列表转换为字符串。
在C#中,将一个字符串列表转换为字符串可以使用`string.Join()`方法。下面是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> stringList = new List<string>() { "Hello", "World", "CSDN" };
string result = string.Join(", ", stringList);
Console.WriteLine(result);
}
}
```
在上述示例中,我们创建了一个字符串列表`stringList`,其中包含三个字符串。然后,使用`string.Join()`方法将列表中的元素连接成一个字符串,并指定用于分隔元素的分隔符。在此示例中,我们使用逗号和空格作为分隔符。
输出结果将是:`Hello, World, CSDN`。
希望能对您有所帮助!如果您有其他问题,请随时提出。
List<String>转List<long>
以下是两种将List<String>转换为List<Long>的方法:
1. 使用Java 8的Stream API:
```java
List<String> list1 = Arrays.asList("123", "456", "789");
List<Long> list2 = list1.stream().map(Long::parseLong).collect(Collectors.toList());
```
2. 使用Apache Commons Collections库的CollectionUtils类:
```java
List<String> list1 = Arrays.asList("123", "456", "789");
List<Long> list2 = new ArrayList<>();
CollectionUtils.collect(list1, new Transformer() {
@Override
public Object transform(Object o) {
return Long.parseLong(o.toString());
}
}, list2);
```