把一个字符串"1,2,3"以逗号分割,加入一个long类型的集合
时间: 2024-02-01 14:13:27 浏览: 84
可以使用 Java 中的 String 类的 split() 方法将字符串以逗号分割成一个字符串数组,然后遍历该数组将每个字符串转换成 long 类型并加入到集合中。下面是示例代码:
```java
String str = "1,2,3";
String[] strArr = str.split(",");
List<Long> list = new ArrayList<>();
for (String s : strArr) {
list.add(Long.parseLong(s));
}
```
这样就可以将字符串"1,2,3"以逗号分割并转换成 long 类型加入到集合中。
相关问题
String supplierIds这个字符串根据逗号进行分隔,变成一个Long类型的集合
`String supplierIds` 这个字符串如果存储了一组用逗号分隔的供应商ID列表,你可以通过Java的`split()`方法将其转换成一个`Long`类型的集合。以下是一个示例:
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public List<Long> convertSupplierIdsToList(String supplierIds) {
String[] ids = supplierIds.split(",");
List<Long> longList = new ArrayList<>();
for (String id : ids) {
longList.add(Long.parseLong(id.trim())); // 使用trim去除前后空格并转换为Long
}
return longList;
}
```
在这个例子中,首先使用逗号`","`作为分隔符将字符串切分成数组,然后遍历每个子串,去掉两端的空白字符,再将其转换为`Long`类型并添加到列表中。
将string集合转化为一个字符串,以逗号间隔
将String集合转化为一个以逗号分隔的字符串,在Java中可以使用`Joiner`类或者循环遍历的方式。以下是两种常见方法:
1. 使用Java 8及更高版本的`Joiner`类:
```java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
List<String> stringList = Arrays.asList("元素1", "元素2", "元素3");
String commaSeparatedString = String.join(",", stringList);
```
这里`String.join()`方法接受一个分隔符作为参数,然后连接整个列表。
2. 循环遍历并手动拼接:
```java
List<String> stringList = ...; // 不管是ArrayList还是其他类型的集合
StringBuilder sb = new StringBuilder();
for (int i = 0; i < stringList.size(); i++) {
if (i > 0) {
sb.append(","); // 第一次迭代跳过
}
sb.append(stringList.get(i));
}
String commaSeparatedString = sb.toString();
```
这两种方法都会得到类似"元素1, 元素2, 元素3"这样的结果。
阅读全文
相关推荐
















