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 frameworkGuava.
StringJoiner Constructors
This class takes two constructors:
- StringJoiner (delimiter) – Adds only the delimiter between the strings
- StringJoiner (delimiter, prefix, suffix) – It adds delimiter, prefix and suffix for each string.
StringJoiner Methods
StringJoiner class defines four methods.
- add(CharSequence newEle) – This method adds the new string into the object.
- length() – It returns the total length of the string joiner object.
- setEmptyOutput(CharSequence charSeq).
- toString() – Returns the current value.
StringJoiner Example
package com.java.example;
import java.util.StringJoiner;
/**
* Java 8 StringJoiner Example
* @author mohan
*
*/
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("Mohan").add("Singh").add("Thakur");
System.out.println("Delimeter, Suffix and Prefix: " + 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 : [Mohan,Singh,Thakur] Length of StringJoiner : 20