Some time we want a function that can join multiple strings in Java . If we are working with other programming languages , we have join() function to join multiple string,If you were using Java you could not do this.Java provided tools for building GUI applications, accessing databases, sending stuff over the network, doing XML transformations or calling remote methods,but a useful collection of string join function not included. For that we have to create our own function or we have to use third party library .
Now java -8 provide StringJoiner Class. By using this class we can join multiple String by using delimiter.
These are some following example .
StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"
// add() calls can be chained
joined = new StringJoiner("-")
.add("foo")
.add("bar")
.add("baz")
.toString(); // "foo-bar-baz"
If I wrote a utility function to join strings using StringBuilder, would it be better to use StringJoiner (performance/efficiency wise) or would it be the same?
What is the difference between StringBuilder and StringJoiner?
There is no such big performance issue . Only StringJoiner makes our code much smaller and readable. For more details you can see doc. https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html.