Oct 15, 2015

Java 8 | StringJoiner

Java 8 has introduced a new String manipulation API StringJoiner, using which one can append multiple string values within the pre-defined format like commas, prefix and suffix.

public final class StringJoiner extends Object

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.

Constructor and Description
Constructs a StringJoiner with the supplied infix delimiter.

StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
Constructs a StringJoiner using copies of the supplied prefix, delimiter and suffix.


For example:
To construct the following String using StringJoiner separated by an infix delimiter and starting with a prefix and ending with a suffix:
[John:Katy:Fred] 

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


Method and Description
Adds new string into the StringJoiner object.
int length()
Returns the length of the String representation of the StringJoiner object.
Sets the sequence of characters to be used when the string representation of the StringJoiner is empty.
Returns the String representation.


It can particularly be useful when creating a formatted output from a Stream using Collectors.joining(CharSequence). For example:

 List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
 String commaSeparatedNumbers = numbers.stream()
.map(i -> i.toString())
.collect(Collectors.joining(", "));

That’s OK if you are not familiar with Lambda expressions, used in example above. Will cover the same in coming tutorials. Subscribe at +Java Territory to stay updated.

0 comments:

Post a Comment