How to use StringJoiner in Java 8, how to splice strings

The StringJoiner provided in Java 8, this article will introduce the recruits of this string splicing.

If you want to know how many ways there are to concatenate strings, I will teach you a simple way. In Intellij IDEA, define a Java Bean, and then try to use shortcut keys to automatically generate a toString method. IDEA will prompt you to generate multiple toStrings. Strategies are available.

![][2]

At present, the toString generation strategy of IDEA I use defaults to use the StringJoiner provided by JDK 1.8.

introduce

StringJoiner is a class in the java.util package that is used to construct a sequence of characters separated by a delimiter (optional), and which can start with the provided prefix and end with the provided suffix. While this is also possible with the help of the StringBuilder class to append a delimiter after each string, StringJoiner provides easy way to do it without writing a lot of code.

The StringJoiner class has 2 constructors and 5 public methods. The most commonly used methods are the add method and the toString method, which are similar to the append method and toString method in StringBuilder.

usage

The usage of StringJoiner is relatively simple. In the following code, we use StringJoiner for string splicing.

public class StringJoinerTest {

    public static void main(String[] args) {
        StringJoiner sj = new StringJoiner("Hollis");

        sj.add("hollischuang");
        sj.add("Java干货");
        System.out.println(sj.toString());

        StringJoiner sj1 = new StringJoiner(":","[","]");

        sj1.add("Hollis").add("hollischuang").add("Java干货");
        System.out.println(sj1.toString());
    }
}

The output of the above code is:

hollischuangHollisJava干货
[Hollis:hollischuang:Java干货]

It is worth noting that when we StringJoiner(CharSequence delimiter)initialize one StringJoiner, this delimiteris actually a separator, not the initial value of the variable string.

StringJoiner(CharSequence delimiter,CharSequence prefix,CharSequence suffix)The second and third parameters of are respectively the prefix and suffix of the concatenated string.

principle

After introducing the simple usage, let's take a look at the principle of this StringJoiner and see how it is implemented. Mainly look at the add method:

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

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

I saw a familiar figure - StringBuilder, yes, StringJoiner is actually implemented by relying on StringBuilder.

When we find that StringJoiner is actually implemented by StringBuilder, we can probably guess that its performance loss should be similar to that of using StringBuilder directly !

Why StringJoiner is needed

After understanding the usage and principle of StringJoiner, many readers may have a question, obviously there is already a StringBuilder, why should a StringJoiner be defined in Java 8? What are the benefits?

If the reader knows enough about Java 8, you may be able to guess that it must be related to Stream.

The author also found the answer in [Java doc][3]:

A StringJoiner may be employed to create formatted output from a Stream using Collectors.joining(CharSequence)

Just imagine, in Java, if we have such a List:

List<String> list = ImmutableList.of("Hollis","hollischuang","Java干货");

If we want to concatenate it into a string of the following form:

Hollis,hollischuang,Java干货

Can be done in the following ways:

StringBuilder builder = new StringBuilder();

if (!list.isEmpty()) {
    builder.append(list.get(0));
    for (int i = 1, n = list.size(); i < n; i++) {
        builder.append(",").append(list.get(i));
    }
}
builder.toString();

You can also use:

list.stream().reduce(new StringBuilder(), (sb, s) -> sb.append(s).append(','), StringBuilder::append).toString();

However, the output is slightly different and requires secondary processing:

Hollis,hollischuang,Java干货,

You can also use "+" for concatenation:

list.stream().reduce((a,b)->a + "," + b).toString();

In the above methods, either the code is complicated, or the performance is not high, or the desired result cannot be obtained directly.

In order to meet requirements like this, the StringJoiner provided in Java 8 comes in handy. The above requirements only need one line of code:

list.stream().collect(Collectors.joining(":"))

That's it. In the expression used above, the source code of Collectors.joining is as follows:

public static Collector<CharSequence, ?, String> joining(CharSequence delimiter,
                                                         CharSequence prefix,
                                                         CharSequence suffix) {
    return new CollectorImpl<>(
            () -> new StringJoiner(delimiter, prefix, suffix),
            StringJoiner::add, StringJoiner::merge,
            StringJoiner::toString, CH_NOID);
}

The realization principle is to use StringJoiner.

Of course, it seems that similar functions can be achieved Collectorby using it directly in , but it is a little more troublesome. StringBuilderTherefore, Java 8 provides StringJoinerrich Streamusage.

And StringJoinerit is also convenient to add prefixes and suffixes. For example, if the string we want to get is [Hollis,hollischuang,Java干货]not Hollis,hollischuang,Javadry goods, the advantages of StringJoiner are even more obvious.

Summarize

This article introduces the variable string class provided in Java 8 - StringJoiner, which can be used for string splicing.

StringJoiner is actually implemented through StringBuilder, so its performance is similar to that of StringBuilder, and it is also non-thread-safe.

If string splicing is required in daily development, how to choose?

1. If it is just simple string concatenation, consider using "+" directly.

2. If string concatenation is performed in a for loop, consider using StringBuilderand StringBuffer.

3. If it is Liststring splicing through one, consider using it StringJoiner.

Guess you like

Origin blog.csdn.net/zy_dreamer/article/details/132350399