StringJoiner

 

SStringJoiner 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.

import java.util.StringJoiner;

public class StringJoinerDemo {

	public static void main(String[] args) {
		String delimeter = "-";
		StringJoiner names = new StringJoiner(delimeter);
		
		names.add("Laulau");
		names.add("Kinga");
		names.add("Fusi");
		
		System.out.println(names);
	}
}

Result:

Laulau-Kinga-Fusi

 

Using prefix and suffix

public static void demoWithPrefixAndSuffix() {
		String delimeter = ",";
		String prefix = "(";
		String suffix = ")";
		StringJoiner names = new StringJoiner(delimeter, prefix, suffix);
		
		names.add("Laulau");
		names.add("Kinga");
		names.add("Fusi");
		
		System.out.println(names);
}

Result:

(Laulau,Kinga,Fusi)

Using merge

public static void demoWithMerge() {
		String delimeter = ",";
		String prefix = "(";
		String suffix = ")";
		StringJoiner names1 = new StringJoiner(delimeter, prefix, suffix);

		names1.add("Laulau");
		names1.add("Kinga");
		names1.add("Fusi");

		System.out.println(names1);

		StringJoiner names2 = new StringJoiner(delimeter, prefix, suffix);

		names2.add("John");
		names2.add("Peter");
		names2.add("Andrew");

		System.out.println(names2);
		
		StringJoiner names3 = names1.merge(names2);
		
		System.out.println(names3);
}

Result:

(Laulau,Kinga,Fusi)
(John,Peter,Andrew)
(Laulau,Kinga,Fusi,John,Peter,Andrew)

 

 

 

 

 

 

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *