When to use StringJoiner over StringBuilder?
Last Updated :
11 Aug, 2021
Prerequisite: StringJoiner
StringJoiner is very useful, when you need to join Strings in a Stream.
Task : Suppose we want the string “[George:Sally:Fred]”, where we have given a string array that contains “George”, “Sally” and “Fred”.
StringJoiner provide add(String str) method to concatenate the strings based on supplied delimiter,prefix and suffix in the constructor, but if we use StringBuilder to perform our task then first we have to append prefix and then iterate through string array and append the required delimiter after each element and finally append the prefix. Below is the java program to demonstrate both ways.
Java
import java.util.StringJoiner;
public class Test
{
public static void main(String[] args)
{
String str[] = { "George" , "Sally" , "Fred" };
StringJoiner sj = new StringJoiner( ":" , "[" , "]" );
sj.add( "George" ).add( "Sally" ).add( "Fred" );
String desiredString = sj.toString();
System.out.println(desiredString);
StringBuilder sb = new StringBuilder();
sb.append( "[" );
if (str.length> 0 )
{
sb.append(str[ 0 ]);
for ( int i = 1 ; i < str.length; i++)
{
sb.append( ":" ).append(str[i]);
}
}
sb.append( "]" );
String desiredString1 = sb.toString();
System.out.println(desiredString1);
}
}
|
Output:
[George:Sally:Fred]
[George:Sally:Fred]
Share your thoughts in the comments
Please Login to comment...