1.背景
JDK8里面的字符串拼接工具类:java.util.StringJoiner ,非线程安全,因为它里面有个非线程安全的成员属性StringBuilder value 来工作的。
2. 使用
@Test
public void spinStringByStringJoiner(){
List<String> lists = new ArrayList<>();
StringJoiner joiner = new StringJoiner("|", "pre[ ", " ]suffix");
lists.add("i");
lists.add("love");
lists.add("you");
//lists.forEach((s)->joiner.add(s));
lists.forEach(joiner::add);
System.out.println("joiner = " + joiner);
}
执行结果:
3.构造方法学习
// 3.1. 只带分隔符的构造方法
public StringJoiner(CharSequence delimiter) {
this(delimiter, "", "");
}
// 3.2.分隔符,前缀,后缀的构造方法
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;
}
4.小结
使用JDK8里面的非线程安全工具类StringJoiner,可以优雅的进行字符串的拼接。