Home >Java >javaTutorial >Detailed code explanation of Java8 StringJoiner

Detailed code explanation of Java8 StringJoiner

黄舟
黄舟Original
2017-03-24 11:02:091807browse

Finally, Java 8 released the StringJoiner class under the java.util package. I don't think this is a radically different implementation than our old-school approach of using StringBuffer/StringBuilder to concatenate strings. Let's take a look at the usage of StringJoiner and its internal implementation. For example, I have two strings called "Smart" and "Techie", and I want to concatenate these strings into [Smart, Techie]. In this case, my prefix is ​​"[", suffix is ​​"]", and delimiter is ",". StringJoiner has the following two

constructors

.

StringJoiner(CharSequence delimiter)
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
We want to have prefixes and suffixes, so use the second constructor in the 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 prefix and suffix, then just:

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

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

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

prepareBuilder() is implemented as follows.

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

From the above implementation, it is obvious that StringJoiner follows the old-fashioned approach.

toString() is implemented as follows.

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

The above is the detailed content of Detailed code explanation of Java8 StringJoiner. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn