神刀安全网

Java 8 StringJoiner – Old Wine With a New Bottle

Java 8 StringJoiner – Old Wine With a New Bottle

Ultimately Java 8 shipped with StringJoiner class under the java.util  package. I don’t think it is a very different implementation to join the strings compared to our old school approach by using StringBuffer/StringBuilder. We will see the usage of the StringJoiner and the internal implementation of it.

For example, I have two strings as “Smart” and “Techie” and I want join those Strings as [Smart,Techie]. In this case, I have the prefix as “[” , the suffix as “]” and the delimiter as “,”.  StringJoiner has two constructors as given below.

StringJoiner(CharSequence delimiter)
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

We want to have prefix and suffix, hence we will use the second constructor for our example.

StringJoiner sjr = new StringJoiner(",", "[", "]"); sjr.add("Smart").add("Techie"); System.out.println("The final Joined string is " + sjr);

If we don’t want to have the prefix and suffix, then:

StringJoiner sjr1 = new StringJoiner(","); sjr1.add("Smart").add("Techie"); System.out.println("The final Joined string is " + sjr1);

Now, we will see the implementation of add and toString() method.

public StringJoiner add(CharSequence newElement) {    prepareBuilder().append(newElement);    return this; }

The prepareBuilder() implementation is given below.

private StringBuilder prepareBuilder() {     if (value != null) {        value.append(delimiter);     } else {        value = new StringBuilder().append(prefix);     }     return value; }

From the above implementations it is evident that the StringJoiner follows an old school approach.

The toString() implementation is given below.

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;     } }

Happy Learning!!!

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Java 8 StringJoiner – Old Wine With a New Bottle

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址