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

package javabeat.net.core;

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(",");
		joiner.add("Java").add("Scala").add("Groovy");
		System.out.println("Delimeter Only:  " + joiner);

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

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

Output…

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

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. sreenath ravva says:

    Cool, nice one , thanks for posting such a simple and good things

Speak Your Mind

*