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:
- 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 newElement) – This method adds the new string into the object.
- length() – It returns the total length of the string joiner object
- setEmptyOutput(CharSequence emptyOutput)
- 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