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

Detailed code explanation of Java8 StringJoiner

黄舟
Release: 2017-03-24 11:02:09
Original
1804 people have browsed it

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

.

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);
Copy after login

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);
Copy after login

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

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

prepareBuilder() is implemented as follows.

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

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;
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template