How to join Strings by a separator in Java 8 / How to join a set of Strings by a separator alongwith prefix and suffix in java

Problem

Suppose there is a bunch of String objects and you want to join them by a separator to form a combined string. For Example, I have 3 strings “www”, “codippa” and “com”. I want to join these strings with a “.”(dot). Normal approach would be :

String s1 = “www”;
String s2 = “codippa”;
String s3 = “com”;
String joinedString = s1 + “.” + s2 + “.” + s3;

This approach is fine but only when the number of strings to be joined is less. When the string values to be joined are more, this approach has following shortcomings:

  1. Code will be more cluttered. Imagine the above line of code with s1 to s15. It will be too lengthy and will look highly unprofessional.
  2. Joining a string with another string creates a new object every time. So 15 strings added means 15 new objects created which means more memory usage. This one is serious !!!

Solution

Java 8 provides the solution to the above problem in the form of java.util.StringJoiner class. This class can automatically add the required separator in between the strings with an added advantage of prefixing and suffixing the result with the desired characters. Using this class is pretty simple.
Initialize its object with the required separator and just add the strings you need to join by calling its add method and it will automatically join those strings with the configured separator. This class has following constructors :

  1. public StringJoiner(CharSequence delimiter) : Takes the separator to be added between the strings as argument.
  2. public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix) : Takes 3 arguments : the separator to be added, the prefix to be added to the result and the suffix to be added to the result.

Code example using both the constructor forms is given below:

import java.util.StringJoiner;

public class StringJoinerExample {

	public static void main(String[] args) {
		// initialize StringJoiner with only separator as argument
		StringJoiner joinerWithSeparatorOnly = new StringJoiner(".");
		// add strings to combine with the separator
		joinerWithSeparatorOnly.add("www");
		joinerWithSeparatorOnly.add("codippa");
		joinerWithSeparatorOnly.add("com");
		System.out.println("Joined String is :");
		System.out.println(joinerWithSeparatorOnly);

		System.out.println("------------------------");
		// initialize StringJoiner with separator, prefix and suffix as
		// arguments
		StringJoiner joinerWithSuffixAndPrefix = new StringJoiner(".", "[", "]");
		// add strings to combine with the separator
		joinerWithSuffixAndPrefix.add("www");
		joinerWithSuffixAndPrefix.add("codippa");
		joinerWithSuffixAndPrefix.add("com");
		System.out.println("Joined String With Prefix and Suffix is :");
		System.out.println(joinerWithSuffixAndPrefix);
	}
}

Output

Joined String is :
www.codippa.com
————————
Joined String With Prefix and Suffix is :
[www.codippa.com]

Instead of calling add method of multiple times in different lines, it can be called in single line as :

joinerWithSeparatorOnly.add(“www”).add(“codippa”).add(“com”);

One would say that we can use java.lang.StringBuffer or java.lang.StringBuilder to add the strings with no extra objects created. Yes, you can but for that you need to create a new object of these classes within your code. Further, to join 5 Strings with 4 separators in between you need to call their append method 9 times. Adding a prefix and suffix before the resultant string makes it to 11. This will again make the code cluttered. Thus using java.util.StringJoiner is a more cleaner approach.

Let’s tweak in :

  1. StringJoiner internally uses java.lang.StringBuilder to hold the string value.
  2. add method of StringJoiner returns an object of StringJoiner only. So instead of calling add method in different lines, they can be called one after another in the same line as shown above.
  3. When printing a StringJoiner object, its toString() method is called which returns the current value stored in this object.
  4. If you are using the constructor which uses prefix and suffix, you cannot set these to null otherwise a java.lang.NullPointerException will be thrown.
sdasdasd

Leave a Reply