Skip to content

Join strings using StringJoiner in Java

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.

Syntax

StringJoiner(CharSequence delimiter)
  
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
Advertisements

Examples

StringJoiner stringJoiner = new StringJoiner(",");
String str = stringJoiner.add("one").add("two").add("three").toString();
System.out.println(str);
//one,two,three
 
stringJoiner = new StringJoiner(",", "[ ", " ]");
stringJoiner.add("Poop").add("Code");
str = stringJoiner.toString();
 
System.out.println(str);
//[Poop,Code]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.