Java 8 - StringJoiner with examples
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. Internally StringJoiner uses the String.join()
Lets see simple examples with various uses of StringJoiner class.
- Joning string by delimiter
- Other way to join string with delimiter
- List to string
- Adding delimiter, prefix and suffix
- Using setEmptyValue() method
- Using setEmptyValue() method - Same after adding some value
- Merging 2 string joiner
public class StringJoiners { public static void main(String[] args) { //Joning string by delimiter StringJoiner sj = new StringJoiner(","); sj.add("Java"); sj.add("Discover"); sj.add("2018"); System.out.println("Joning string by delimiter :: "+ sj.toString()); //Other way to join string with delimiter String str = String.join(",", "JAVA", "DISCOVER", "2018"); System.out.println("\nOther way : "+str); //List to string List<String> list = Arrays.asList("Java", "String", "Joiner"); String str1 = String.join(", ", list); System.out.println("\nList to string : "+str1); //Adding delimiter, prefix and suffix StringJoiner sj1 = new StringJoiner(".","Hello "," :)"); sj1.add("Java"); sj1.add("Discover"); sj1.add("2018"); System.out.println("\nAdding delimiter, prefix and suffix :: "+ sj1.toString()); /* * Using setEmptyValue() method - set default value of the string * if string is empty */ StringJoiner sj2 = new StringJoiner("*"); sj2.setEmptyValue("DEFUALT EMPTY STRING"); System.out.println("\nUsing setEmptyValue() method-1 :: "+ sj2.toString() + " ---- LENGTH : "+sj2.toString().length());
// Same after adding some value sj2.add("ORACLE"); sj2.add("LAMBDA"); System.out.println("\nUsing setEmptyValue() method-2 :: "+ sj2.toString() + " ---- LENGTH : "+sj2.toString().length()); //Merging 2 string joiner StringJoiner sj3 = sj1.merge(sj2); System.out.println("\nMerging 2 string joiner :: "+sj3.toString()); } }
OUTPUT:
Joning string by delimiter :: Java,Discover,2018 Other way : JAVA,DISCOVER,2018 List to string : Java, String, Joiner Adding delimiter, prefix and suffix :: Hello Java.Discover.2018 :) Using setEmptyValue() method-1 :: DEFUALT EMPTY STRING ---- LENGTH : 20 Using setEmptyValue() method-2 :: ORACLE*LAMBDA ---- LENGTH : 13 Merging 2 string joiner :: Hello Java.Discover.2018.ORACLE*LAMBDA :)