StringJoiner in Java 8

22 / Jun / 2016 by Nishant Lakra 1 comments

Being a programmer, at some point of time we encountered a situation in which you wanted to join (not concat) multiple strings of delimited items in Java. Worst can be if you are provided multiple string literals. Just think for a second and how will you build a string of delimited items using these literals. Eg.

String str1 = "java";
String str2 = "scala";
String str3 = "groovy";

StringBuilder sb = new StringBuilder();

Or, many times we find ourselves in a situation where you want to pass a collection to IN clause of HQL or SQL. In this era of programming this is how we do this so obvious work

// List<String> listOfNames = ....
 StringBuilder sbObj = new StringBuilder();
 for (String str : listOfNames) {
   if (sbObj.length() > 0) {

Code reviewer will acquit you due to lack of good solutions evidence. But not anymore, In Java 8 we finally can join Strings with ease.

StringJoiner is a class added in Java 8. As the name suggests, we can use this class to join strings. There are two constructors, one taking the separator (delimiter) and one allowing a prefix and suffix.

1. StringJoiner(CharSequence delimiter)

StringJoiner joiner = new StringJoiner(",");
String desiredStr = joiner.toString(); // "java,scala,groovy"

// add() calls can be chained
 joined = new StringJoiner("-")
         .toString(); // "java-scala-groovy"

2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

The String like “[Richard:Gilfoyle:Erlich]” may be constructed as follows:

StringJoiner sj = new StringJoiner(":", "[", "]");
String desiredString = sj.toString();

Moreover, StringJoiner is used as a behind scene tool by the two new static join() methods of String class:

//  join(CharSequence delimiter, CharSequence… elements)

 String joined = String.join("/", "2016", "06", "15" ); // "2016/06/15"

// join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

 List<String> list = Arrays.asList("java", "scala", "groovy");
 joined = String.join(";", list); // "java;scala;groovy"

A new joining Collector is also available for the new Stream API:

List<Employee> list = Arrays.asList(
                        new Employee("Richard", "Hendriks"),
                        new Employee("Erlich", "Bachmann"),
                        new Employee("Jared", "Dunn ")

String joinedFirstNames =

// "Richard, Erlich, Jared"

Now,  join string smartly ;-)

Tag -

Java java8 String

comments (1 “StringJoiner in Java 8”)

Leave a comment -