把逗号分隔的String字符串转int集合
集合或数组转变为逗号分隔的字符串的几种方式
1、自己编码实现
2、org.apache.commons.lang3.StringUtils
3、StringJoiner, JDK1.8+
4、String.join(), JDK1.8+
5、Stream, Collectors.joining(), JDK1.8+
把逗号分隔的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();
}
输出
2、org.apache.commons.lang3.StringUtilsnull,bob,jack
System.out.println(StringUtils.join(list.toArray(), ","));
输出
3、StringJoiner, JDK1.8+,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());
输出
4、String.join(), JDK1.8+null,bob,jack
START_null,bob,jack_END
System.out.println(String.join(",", list));
输出
5、Stream, Collectors.joining(), JDK1.8+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
以上为个人经验,希望能给大家一个参考,也希望大家多多支持易知道(ezd.cc)。