Python 官方文档:入门教程 => 点击学习
目录把逗号分隔的String字符串转int集合集合或数组转变为逗号分隔的字符串的几种方式1、自己编码实现2、org.apache.commons.lang3.StringUtils3
代码通过Java 8 Stream实现起来非常容易!
String ids = "1,2,3,4,5";
List<Integer> idList = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
首先,创建一个集合
List<String> list = Lists.newArrayList(null, "bob", "jack");
public static <T> String join(List<T> list, String splitStr) {
if (CollectionUtils.isEmpty(list))
return "";
if (list.size() == 1)
return String.valueOf(list.get(0));
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (int i = 0; i < list.size(); i++) {
if (!isFirst) sb.append(splitStr);
sb.append(String.valueOf(list.get(i)));
isFirst = false;
}
return sb.toString();
}
public static <T> String join(T[] array, String splitStr) {
if (ArrayUtils.isEmpty(array))
return "";
if (array.length == 1)
return String.valueOf(array[0]);
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (int i = 0; i < array.length; i++) {
if (!isFirst) sb.append(splitStr);
sb.append(String.valueOf(array[i]));
isFirst = false;
}
return sb.toString();
}
输出
null,bob,jack
System.out.println(StringUtils.join(list.toArray(), ","));
输出
,bob,jack
StringJoiner sj = new StringJoiner(",");
list.forEach(e -> sj.add(String.valueOf(e)));
System.out.println(sj.toString());
// 在连接之前操作字符串, 拼接前缀和后缀
StringJoiner sj2 = new StringJoiner(",", "START_", "_END");
list.forEach(e -> sj2.add(String.valueOf(e)));
System.out.println(sj2.toString());
输出
null,bob,jack
START_null,bob,jack_END
System.out.println(String.join(",", list));
输出
null,bob,jack
System.out.println(list.stream().collect(Collectors.joining(",")));
// 在连接之前操作字符串, 拼接前缀和后缀
String str = list.stream().map(e -> {
if (e != null) return e.toUpperCase();
else return "null";
}).collect(Collectors.joining(",", "START_", "_END"));
System.out.println(str);
输出
null,bob,jack
START_null,BOB,JACK_END
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: java如何把逗号分隔的String字符串转int集合
本文链接: https://lsjlt.com/news/153062.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0