StringJoiner in Java 8

Datetime:2016-08-23 00:38:09          Topic: Java8           Share

June 22, 2016 by Nishant Lakra | 0 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();
sb.append(str1).append(",").append(str2).append(",").append(str3);
sb.toString();

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) {
      sbObj.append(',');
   }
   sbObj.append(str);
 }
 sbObj.toString();

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(",");
joiner.add("java");
joiner.add("scala");
joiner.add("groovy");
String desiredStr = joiner.toString(); // "java,scala,groovy"

// add() calls can be chained
 joined = new StringJoiner("-")
         .add("java")
         .add("scala")
         .add("groovy")
         .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(":", "[", "]");
sj.add("Richard").add("Gilfoyle").add("Erlich");
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 = list.stream()
                              .map(Employee::getFirstName)
                              .collect(Collectors.joining(","));

// "Richard, Erlich, Jared"

Now,  join string smartly





About List