publicclassStringJoinerTest1{ publicstaticvoidmain(String[] args){ StringJoiner joiner = new StringJoiner("--", "[[[_ ", "_]]]"); System.out.println(joiner.toString()); System.out.println(joiner.length()); } } // result [[[_ _]]] 9
API介绍
StringJoiner 是 java8 新增的类。
构造器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicStringJoiner(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; }
public StringJoiner add(CharSequence newElement){ prepareBuilder().append(newElement); returnthis; }
1 2 3 4 5 6 7 8
private StringBuilder prepareBuilder(){ if (value != null) { value.append(delimiter); } else { value = new StringBuilder().append(prefix); } return value; }
1 2 3 4 5 6 7
public AbstractStringBuilder append(CharSequence s){ if (s == null) return appendNull(); if (s instanceof String) returnthis.append((String)s); if (s instanceof AbstractStringBuilder) returnthis.append((AbstractStringBuilder)s); returnthis.append(s, 0, s.length()); }
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(); value.setLength(initialLength); return result; } } }
value == null, 返回 空。
不为空,判断 是否需要添加 后缀
length:
1 2 3 4 5 6 7 8
publicintlength(){ // 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()); } }
value 不为 null ,返回 value的长度 + 后缀长度(不为null时,已经计算了value+前缀)
merge:
1 2 3 4 5 6 7 8
StringJoiner joiner = new StringJoiner("--", "[[[_", "_]]]"); joiner.add("1").add("2").add("3").add("4");
StringJoiner joiner2 = new StringJoiner("..."); joiner2.add("a").add("b").add("c");
public StringJoiner merge(StringJoiner other){ Objects.requireNonNull(other); if (other.value != null) { finalint 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); } returnthis; } // result [[[_1--2--3--4--a...b...c_]]]