StringJoiner java 8
Java 8 added a new class StringJoiner, which is used to join strings with a separator. With StringJoiner, you can also add prefix and suffix strings to the result.

Example, with StringJoiner, you can join strings “learning”, “java”, “online” with “-“ as a separator to form “learning-java-online” as the result.
StringJoiner is added in java.util package and it is a final class.
This article will explain how to use StringJoiner in java 8 to combine string values, its syntax with example programs.

Creating StringJoiner
To use StringJoiner, its instance or object needs to be created using any of its below constructors.
1. StringJoiner(CharSequence delimiter)
This constructor takes a String argument which is the delimiter or separator between the strings to be joined.

2. StringJoiner(CharSequence delimiter,
                               CharSequence prefix, CharSequence suffix)
This constructor takes 3 string arguments which represent:
A. Delimiter or separator between the strings to be joined.
B. Prefix which will be added before the result.
C. Suffix which will be added after the result. Example,

new StringJoiner(“,”, “{“, “}” );

Here, the separator is a comma and the resultant string will be surrounded between { and }.
Adding Strings
Strings to be joined are added using add() method of StringJoiner. add() takes a string argument which is added after the other strings as shown below

StringJoiner j = new StringJoiner(",");
j.add("learning");
j.add("java");

Note that add() returns the same StringJoiner object on which it was called. So, instead of calling add() separately everytime, you can chain multiple calls as below.

StringJoiner j = new StringJoiner(","); 
j.add("learning").add("java");

StringJoiner example
Below is a complete example of StringJoiner which adds multiple strings separated by a delimiter.

public class StringJoinerExample {
  public static void main(String[] args) throws IOException {
    // create object
    StringJoiner j = new StringJoiner("-");
    // add strings
    j.add("learning").add("java").add("is").add("fun");
    System.out.println(j.toString());
  }
}

This prints

learning-java-is-fun

StringJoiner : prefix and suffix
As stated above, StringJoiner allows you to add prefix and suffix around the joined strings.
For defining prefix and suffix, create StringJoiner with a constructor that takes 3 arguments. Example,

public class StringJoinerExample { 
  public static void main(String[] args) throws IOException { 
    // create object 
    StringJoiner j = new StringJoiner("-", "[", "]"); 
    // add strings 
    j.add("learning").add("java").add("is").add("fun"); 
    System.out.println(j.toString()); 
  } 
}

Output is

[learning-java-is-fun]

Merge StringJoiners
Different StringJoiner objects can be merged to form a single string value using its merge() method.
merge() is invoked on a StringJoiner object and takes another object as argument. It joins the contents to the argument StringJoiner to the object on which it is invoked.
This means that the object on which it is called is modified while the argument object remains unmodified. Example,

// create first StringJoiner
StringJoiner j1 = new StringJoiner(",");
j1.add("learning").add("java");
// create second StringJoiner		
StringJoiner j2 = new StringJoiner(",");
j2.add("is").add("fun");
// merge both
j1.merge(j2);
System.out.println(j1.toString());
System.out.println(j2.toString());

Output is

learning,java,is,fun
is,fun

Argument object remains unchanged while its contents are merged into the invoking object.

StringJoiner vs StringBuilder/StringBuffer
java.lang.StringBuilder or java.lang.StringBuffer are also used for joining multiple strings together using their append() method.
Then why StringJoiner?
The answer is StringJoiner is very easy to use as compared to both these classes. Following are a couple of scenarios to prove this.

1. With StringBuilder or StringBuffer, you need to repeat the separator every time it needs to be added. For adding 4 strings, with a prefix and suffix, StringBuilder will require below code

StringBuilder b = new StringBuilder("[");
b.append("learning").append(",").append("java").
  append(",").append("is").append("fun").append("]");

While with StringJoiner, below code will be used

StringJoiner j = new StringJoiner(",", "[", "]"); 
j.add("learning").add("java").add("is").add("fun");

2. If the strings are joined within a loop, then StringBuilder or StringBuffer will add an extra separator, which needs to be separately removed after the loop as shown below.

List<String> words = List.of("learning", "java", "is", "fun");
StringBuilder b = new StringBuilder("");
for (String word : words) {
  b.append(word).append(",");
}
System.out.println(b.toString());
String result = "";
// remove trailing separator
if(!b.toString().equals("")) {
  result = b.substring(0, b.length()-1);
}
System.out.println(result);

This prints

learning,java,is,fun,
learning,java,is,fun

You can see that simply appending strings also adds an extra separator that needs to be removed explicitly, while there is no such problem with StringJoiner.
StringJoiner methods
Following are some of the important methods of StringJoiner.
1. add(CharSequence s)
It is used to add a string to be joined. We have already looked at this method in action.

2. setEmptyValue(CharSequence value)
When StringJoiner is created using its constructor, it does not contain any value till add() is called.
setEmptyValue() allows you to set an empty value for StringJoiner. The value is supplied as argument. Example,

StringJoiner j = new StringJoiner(",");
System.out.println("Value of StringJoiner: " + j.toString());
j.setEmptyValue("Nothing here!");
System.out.println("Value of StringJoiner: " + j.toString());

This prints

Value of StringJoiner:
Value of StringJoiner: Nothing here!

Remember that empty value is removed as soon as a value is added to StringJoiner.

3. merge(StringJoiner j)
This method merges the contents of argument StringJoiner to the StringJoiner on which it is called. Contents of argument StringJoiner remain unchanged.
merge() returns the same object on which it was called. So, you can chain multiple merge() calls or even apply add() calls after merge as

j.merge(j1).merge(j2).add(“A”);

We have already seen this merge() in action above.

4. length()
length() method returns the number of characters in StringJoiner. This includes the separators, prefix and suffix values. Example,

StringJoiner j = new StringJoiner(",","[","]");
j.add("a").add("b");
System.out.println("Length of StringJoiner: "+j.length());

This prints

Length of StringJoiner: 5

Remember that separators, prefix and suffix are only counted when a string has been added to the StringJoiner.
If it has empty value, then these are not included in length. Example,

StringJoiner j = new StringJoiner(",","[","]");
j.setEmptyValue("nothing");
System.out.println("Length of StringJoiner: "+j.length());

Output is

Length of StringJoiner: 7

which is the length of empty value only.
Hope the article was useful.

1
Liked the article ? Spread the word...