首先,创建一个集合
List list = Lists.newArrayList(null, "bob", "jack");
public static String join(List 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 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