by BehindJava

What is StringJoiner and its uses in Java 8 with an example

Home » interview » What is StringJoiner and its uses in Java 8 with an example

In this blog, we are going to learn about String Joiner and its uses which is introduced in the Java 8.

java.util.StringJoiner

StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

Prior to adding something to the StringJoiner, its sj.toString() method will, by default, return prefix + suffix. However, if the setEmptyValue method is called, the emptyValue supplied will be returned instead. This can be used, for example, when creating a string using set notation to indicate an empty set, i.e. ”{}”, where the prefix is ”{”, the suffix is ”}” and nothing has been added to the StringJoiner.

See Also:\

java.util.stream.Collectors.joining(CharSequence)
java.util.stream.Collectors.joining(CharSequence, CharSequence, CharSequence)

@apiNote

The String ”[George:Sally:Fred]” may be constructed as follows:

 StringJoiner sj = new StringJoiner(":", "[", "]");
 sj.add("George").add("Sally").add("Fred");
 String desiredString = sj.toString();

Example:

import java.util.StringJoiner;

public class BehindJava {

	public static void main(String[] args) {
		StringJoiner st = new StringJoiner(";");
		st.add("Roger").add("copy that").add("black squad");
		System.out.println(st);
		StringJoiner su = new StringJoiner("^");
		su.add("Sanathanm").add("Rolex").add("Delhi");
		st.merge(su);
		System.out.println(st);
	}
}
Roger;copy that;black squad
Roger;copy that;black squad;Sanathanm^Rolex^Delhi