Java StringJoiner - merge() Method
The java.util.StringJoiner.merge() method is used to add the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty. If the given StringJoiner is empty, the call has no effect.
A StringJoiner is empty if add() has never been called, and if merge() has never been called with a non-empty StringJoiner argument.
If the other StringJoiner is using a different delimiter, then elements from the other StringJoiner are concatenated with that delimiter and the result is appended to this StringJoiner as a single element.
Syntax
public StringJoiner merge(StringJoiner other)
Parameters
other |
Specify the StringJoiner whose contents should be merged into this one. |
Return Value
Returns this StringJoiner.
Exception
Throws NullPointerException, if the other StringJoiner is null.
Example:
In the example below, the java.util.StringJoiner.merge() method is used to find out the merge of the given StringJoiner.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a StringJoiner object StringJoiner joinNames1 = new StringJoiner(", ","[","]"); StringJoiner joinNames2 = new StringJoiner(", ","{","}"); //Adding values to joinNames1 joinNames1.add("John"); joinNames1.add("Marry"); //Adding values to joinNames1 joinNames2.add("Kim"); joinNames2.add("Jo"); //printing joinNames1 and joinNames2 System.out.println("joinNames1 contains: " + joinNames1); System.out.println("joinNames2 contains: " + joinNames2); //merging the joinNames2 into joinNames1 joinNames1.merge(joinNames2); //printing joinNames1 after merge System.out.print("\nAfter merge joinNames1 contains: "); System.out.println(joinNames1); } }
The output of the above code will be:
joinNames1 contains: [John, Marry] joinNames2 contains: {Kim, Jo} After merge joinNames1 contains: [John, Marry, Kim, Jo]
❮ Java.util - StringJoiner