StringJoiner是JDK1.8新出的一个类,用于拼接字符串时加入分隔符、前缀、后缀。不需要手动拼接这些与业务无关的符号,也省去处理边界问题的麻烦。
例子:将数组中的元素拼接成以","分割的字符串
String[] strings = new String[]{"a", "b", "c"};
拼接结果:a,b,c
使用StringJoiner之前
public static void main(String[] args) {
String[] strings = new String[]{"a", "b", "c"};
StringBuilder sb = new StringBuilder();
for (String s : strings) {
// 需要在每一次拼接后面加","
sb.append(s).append(",");
}
// 拼接完后还需要将最后一个分隔符","去掉
String substring = sb.substring(0, sb.length() - 1);
System.out.println(substring);
}
使用StringJoiner之后
public static void main(String[] args) {
String[] strings = new String[]{"a", "b", "c"};
// 构造方法参数是分隔符","每次拼接字符串自动加上分隔符
StringJoiner sj = new StringJoiner(",");
for (String s : strings) {
// 直接拼接字符串,无需处理分隔符和边界问题
sj.add(s);
}
System.out.println(sj);
}
StringJoiner有两个构造方法:
一个参数的构造方法,构造一个以delimiter为分隔符的StringJoiner,每次拼接字符串自动加上delimiter分隔符
public StringJoiner(CharSequence delimiter) {
this(delimiter, "", "");
}
三个参数的构造方法,构造一个以delimiter为分隔符的StringJoiner,并且在最终的结果字符串上拼接prefix前缀和suffix后缀。
public StringJoiner(CharSequence delimiter,
CharSequence prefix,
CharSequence suffix) {
Objects.requireNonNull(prefix, "The prefix must not be null");
Objects.requireNonNull(delimiter, "The delimiter must not be null");
Objects.requireNonNull(suffix, "The suffix must not be null");
// make defensive copies of arguments
this.prefix = prefix.toString();
this.delimiter = delimiter.toString();
this.suffix = suffix.toString();
this.emptyValue = this.prefix + this.suffix;
}
add方法
public StringJoiner add(CharSequence newElement) {
prepareBuilder().append(newElement);
return this;
}
private StringBuilder prepareBuilder() {
if (value != null) {
value.append(delimiter);
} else {
value = new StringBuilder().append(prefix);
}
return value;
}
最终是调用的StringBuilder的append方法
public StringBuilder append(CharSequence s) {
super.append(s);
return this;
}