StringJoiner is very useful, when you need to join Strings in a Stream.
Task : Suppose we want the string “[George:Sally:Fred]”, where we have given a string array that contains “George”, “Sally” and “Fred”.
StringJoiner provide add(String str) method to concatenate the strings based on supplied delimiter,prefix and suffix in the constructor, but if we use StringBuilder to perform our task then first we have to append prefix and then iterate through string array and append the required delimiter after each element and finally append the prefix. Below is the java program to demonstrate both ways.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- StringJoiner add() method in Java
- StringJoiner setEmptyValue() method in Java
- StringJoiner toString() method in Java
- StringJoiner merge() method in Java
- Java.util.StringJoiner in Java8
- StringJoiner length() method in Java
- StringBuilder subSequence() in Java with Examples
- StringBuilder setLength() in Java with Examples
- String vs StringBuilder vs StringBuffer in Java
- StringBuilder deleteCharAt() in Java with Examples
- StringBuilder codePointBefore() in Java with Examples
- StringBuilder ensureCapacity() in Java with Examples
- StringBuilder capacity() in Java with Examples
- StringBuilder codePointCount() in Java with Examples
- StringBuilder delete() in Java with Examples