如果需要拼接分隔符的字符串,建议使用 Java 8 中的这款拼接神器:StringJoiner,你值得拥有。
1、拼接
public static void main(String[] args) {
StringJoiner stringJoiner = new StringJoiner(",");
stringJoiner.add("hello");
stringJoiner.add("guys");
stringJoiner.add("欢迎关注Java后端指南");
System.out.println(stringJoiner.toString());
}
结果:
hello,guys,欢迎关注Java后端指南
2、构造方法
源码可以看到两个构造方法
这个是必须带分割符
public StringJoiner(CharSequence delimiter) {
this(delimiter, "", "");
}
这个是必须带分割符,前缀,后缀
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;
}
公开方法:
- setEmptyValue:设置空值
- toString:转换成 String
- add:添加字符串
- merge:从另一个 StringJoiner 合并
- length:长度(包括前缀后缀)
setEmptyValue:
public StringJoiner setEmptyValue(CharSequence emptyValue) {
this.emptyValue = Objects.requireNonNull(emptyValue,
"The empty value must not be null").toString();
return this;
}
toString:
@Override
public String toString() {
if (value == null) {
return emptyValue;
} else {
if (suffix.equals("")) {
return value.toString();
} else {
int initialLength = value.length();
String result = value.append(suffix).toString();
// reset value to pre-append initialLength
value.setLength(initialLength);
return result;
}
}
}
add:
public StringJoiner add(CharSequence newElement) {
prepareBuilder().append(newElement);
return this;
}
merge:
public StringJoiner merge(StringJoiner other) {
Objects.requireNonNull(other);
if (other.value != null) {
final int length = other.value.length();
// lock the length so that we can seize the data to be appended
// before initiate copying to avoid interference, especially when
// merge 'this'
StringBuilder builder = prepareBuilder();
builder.append(other.value, other.prefix.length(), length);
}
return this;
}
length:
public int length() {
// Remember that we never actually append the suffix unless we return
// the full (present) value or some sub-string or length of it, so that
// we can add on more if we need to.
return (value != null ? value.length() + suffix.length() :
emptyValue.length());
}
3、前后缀拼接
StringJoiner stringJoiner = new StringJoiner(",", "[", "]");
stringJoiner.add("hello");
stringJoiner.add("guys");
stringJoiner.add("欢迎关注Java后端指南");
结果:
[hello,guys,欢迎关注Java后端指南]