今天在看一个第三方框架源码的时候,看这StringJoiner这个类,以前在拼接字符串的时候一直使用的StringBuilder,所以特别感兴趣,这里的场景是这样用的,当然这个代码是我自己写的,模拟的用法:

String[] strArr = new String[]{"str1","str2","str3","str4","str5"};
StringJoiner joiner = new StringJoiner(",", "[", "]");
for(String s : strArr){
    joiner.add(s);
}
String s = joiner.toString();
System.out.println(s);

输出的结果:

[str1,str2,str3,str4,str5]

需要使用这种字符串拼接的场景太多,以前一直使用StringBuilder拼接,在需要使用分隔符的时候得自己判断是不是最后一个元素,代码如下:

String[] strArr = new String[]{"str1","str2","str3","str4","str5"};
StringBuilder sb = new StringBuilder("[");
for(int i=0; i<strArr.length; i++){
    sb.append(strArr[i]);
    if(i<(strArr.length-1)){
        sb.append(",");
    }
}
sb.append("]");
String s = sb.toString();
System.out.println(s);

这样一对比,简直太好用了。
直接看了一眼StringJoiner的实现源码,内部仍是基于StringBuilder实现的,且StringBuilder是一个成员变量,因此这个类也是非线程安全的,这是需要注意。源码实现非常简单,大家可以自行翻阅一下:

public final class StringJoiner {
    private final String prefix; //前缀
    private final String delimiter; //分隔符
    private final String suffix; //后缀

    /*
     * StringBuilder value -- at any time, the characters constructed from the
     * prefix, the added element separated by the delimiter, but without the
     * suffix, so that we can more easily add elements without having to jigger
     * the suffix each time.
     */
    private StringBuilder value;

    /**
     * Adds a copy of the given {@code CharSequence} value as the next
     * element of the {@code StringJoiner} value. If {@code newElement} is
     * {@code null}, then {@code "null"} is added.
     *
     * @param  newElement The element to add
     * @return a reference to this {@code StringJoiner}
     */
    public StringJoiner add(CharSequence newElement) {
        prepareBuilder().append(newElement);
        return this;
    }

    ......
}

发表评论