java如何把逗号分隔的String字符串转int集合
作者:itdragons
这篇文章主要介绍了java实现把逗号分隔的String字符串转int集合,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
把逗号分隔的String字符串转int集合
代码通过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");
1、自己编码实现
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
2、org.apache.commons.lang3.StringUtils
System.out.println(StringUtils.join(list.toArray(), ","));
输出
,bob,jack
3、StringJoiner, JDK1.8+
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
4、String.join(), JDK1.8+
System.out.println(String.join(",", list));
输出
null,bob,jack
5、Stream, Collectors.joining(), JDK1.8+
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
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。