java String[]转List<String>
时间: 2024-06-14 10:07:39 浏览: 17
以下是三种将Java中的String数组转换为List<String>的方法:
1. 使用Arrays.asList()方法:
```java
String[] strArray = {"apple", "banana", "orange"};
List<String> list = Arrays.asList(strArray);
```
2. 使用循环遍历并逐个添加到List中:
```java
String[] strArray = {"apple", "banana", "orange"};
List<String> list = new ArrayList<>();
for (String str : strArray) {
list.add(str);
}
```
3. 使用Stream API的Stream.of()方法:
```java
String[] strArray = {"apple", "banana", "orange"};
List<String> list = Stream.of(strArray).collect(Collectors.toList());
```
相关问题
java String 转list<Object>
Java中可以使用split()方法将一个字符串按照指定的分隔符分割成多个子字符串,然后将这些子字符串转换成List<Object>类型。具体实现如下所示:
```java
String str = "1,2,3,4,5";
String[] strArr = str.split(",");
List<Object> list = new ArrayList<>();
for (String s : strArr) {
list.add((Object)s);
}
```
上述代码中,我们首先定义了一个字符串str,然后使用split()方法将其按照逗号分隔成多个子字符串,存储在一个字符串数组strArr中。接着,我们定义了一个List<Object>类型的列表list,并使用for循环遍历strArr数组,将每个子字符串转换成Object类型并添加到列表中。最终,我们得到了一个包含了字符串str中所有元素的List<Object>类型的列表list。
Map<String, List<>>转List<List<>>且均匀分配,List<List<>>大小为20
假设Map<String, List<String>>为例,可以按照以下方式转换成List<List<String>>并进行均匀分配:
```java
Map<String, List<String>> map = new HashMap<>();
// 假设map中已经存储了数据
// 将map转换为List<List<String>>
List<List<String>> resultList = new ArrayList<>();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
resultList.add(list);
}
// 均匀分配,List<List<>>大小为20
int totalSize = resultList.size();
int maxSize = 20;
int groupCount = totalSize % maxSize == 0 ? totalSize / maxSize : totalSize / maxSize + 1;
List<List<List<String>>> groups = new ArrayList<>();
for (int i = 0; i < groupCount; i++) {
int startIndex = i * maxSize;
int endIndex = Math.min(startIndex + maxSize, totalSize);
List<List<String>> group = new ArrayList<>(resultList.subList(startIndex, endIndex));
groups.add(group);
}
```
这段代码中,首先将Map<String, List<String>>转换为List<List<String>>,然后计算出需要分成几组,每组大小为20。最后将List<List<String>>按照均匀分配的规则分成多个List<List<String>>。
相关推荐
![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)