JAVA 中 如何快速的将 List<String> 转换为 List<long>,或者将逗号分隔字符串转换成 List<Long>数组
时间: 2023-06-06 11:05:43 浏览: 2524
可以使用 Java 8 中的流式 API 和 map 方法来实现快速转换。假设需要将 List<String> 转换为 List<Long>,代码如下:
List<String> stringList = Arrays.asList("1", "2", "3");
List<Long> longList = stringList.stream()
.map(Long::valueOf)
.collect(Collectors.toList());
同样地,如果需要将逗号分隔字符串转换为 List<Long> 数组,代码如下:
String str = "1,2,3";
List<Long> longList = Arrays.stream(str.split(","))
.map(Long::valueOf)
.collect(Collectors.toList());
相关问题
List<Long>怎么转换成字符串,以逗号分隔
可以使用Java 8的Stream API和Collectors.joining方法将List<Long>转换成以逗号分隔的字符串。
示例代码如下:
```java
List<Long> list = Arrays.asList(1L, 2L, 3L, 4L, 5L);
String result = list.stream()
.map(Object::toString)
.collect(Collectors.joining(","));
System.out.println(result); // 输出结果为:1,2,3,4,5
```
这段代码首先将List<Long>转换成一个Stream<Long>,然后通过map方法将每个Long对象转换成对应的字符串表示,最后使用Collectors.joining方法将所有字符串连接起来,以逗号分隔。
List<Long>变成用逗号分隔的字符串
可以使用Java 8中的Stream API和Collectors.joining()方法将List<Long>转换为用逗号分隔的字符串。示例如下:
```java
List<Long> list = Arrays.asList(1L, 2L, 3L, 4L, 5L);
String commaSeparatedString = list.stream()
.map(Object::toString)
.collect(Collectors.joining(","));
System.out.println(commaSeparatedString); // 输出: 1,2,3,4,5
```
在上面的示例中,使用stream()方法将List<Long>转换为Stream<Long>,接着使用map()方法将每个Long对象转换为其字符串表示形式,最后使用Collectors.joining(",")方法将所有字符串连接起来,用逗号分隔。