Java 8 StringJoiner Example

Java 8 introduces a new String manipulation API StringJoiner. Using StringJoiner, one can append multiple string values with the pre-defined format like commas, prefix and suffix. This syntax is very similar to the one used with the another framework Guava.

StringJoiner Constructors

This class takes two constructors:

  1. StringJoiner (delimiter) РAdds only the delimiter between the strings
  2. StringJoiner (delimiter, prefix, suffix) – It adds delimiter, prefix and suffix for each string.

StringJoiner Methods

StringJoiner class defines four methods.

  1. add(CharSequence newElement) – This method adds the new string into the object.
  2. length() – It returns the total length of the string joiner object
  3. setEmptyOutput(CharSequence emptyOutput)
  4. toString() – Returns the current value

StringJoiner Example


import java.util.StringJoiner;

 * Java 8 StringJoiner Example
 * @author krishna
public class StringJoinerExample {
	public static void main (String args[]){
		// Only delimiter example
		StringJoiner joiner = new StringJoiner(",");
		System.out.println("Delimeter Only:  " + joiner);

		// Delimiter with prefix and suffix example
		joiner = new StringJoiner(",","[","]");
		System.out.println("Delimeter, Suffix and Prefix Example :  " + joiner);

		//Finding the total length of string joiner
		System.out.println("Length of StringJoiner : "+ joiner.length());


Delimeter Only:  Java,Scala,Groovy
Delimeter, Suffix and Prefix Example :  [Java,Scala,Groovy]
Length of StringJoiner : 19

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>