Java 8 – Understanding String.join() and StringJoiner2 min read

Java

Overview

Prior to Java 8, whenever there was a need to create a comma separated list of elements, we mostly used StringBuilder, or StringBuffer based on the use case.

Well in Java 8, this kind of usage is finally addressed and developers have added utilities like String.join() and StringJoiner class in java.util.

1. Understanding String.join()

Java-doc definition for join() method:

Returns a new String composed of copies of the Char-Sequence elements joined together with a copy of the specified delimiter.

There are two Join methods provided by the String class:

public static String join(CharSequence delimiter, CharSequence... elements)
public static String join(CharSequence delimiter, Iterable<? 
                          extends CharSequence> elements)

Meaning:

String.join() and StringJoiner

1.1 String.join()

String str = String.join(" and ", "one", "two", "three");
System.out.println(str);
output: one and two and three

1.2 String.join() with Arrays

String[] strArr = { "one", "two", "three" };
String numList = String.join(", ", strArr);
System.out.println(numList);
output: one, two, three


2. Understanding StringJoiner class

So far so good, but what if, we wanted to perform more sophisticated operations?

StringJoiner is another utility class added to java.util which brings in more useful functions. Here’s, Java-doc definition for StringJoiner:

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.

2.1 Using StringJoiner

StringJoiner sj = new StringJoiner(", ", "<", ">");
sj.add("A");
sj.add("B");
sj.add("C");
System.out.println(sj);
output: <A, B, C>

Here, we are creating a new StringJoiner objects, parameters StringJoiner(“, “, “<“, “>”); denotes the following:

  • , the delimiter
  • < prefix
  • > suffix

Now, looking at the above output, it is evident as to how these parameters are placed in the resulting output.

2.2 StringJoiner with Merge() method.

StringJoiner sjM = new StringJoiner(", ");
sjM.add("D");
sj.merge(sjM);
System.out.println(sj);
output: <A, B, C, D>

merge() method simply joins the values of the two StringJoiner defined so far.

2.3 StringJoiner with Collections.

List list = new ArrayList<>();
list.add("X");
list.add("Y");
list.add("Z");

StringJoiner sjL = new StringJoiner(" - ");
list.forEach(s -> sjL.add(s));
System.out.println(sjL);
output: X - Y - Z

Here, we have made use of the forEach method to simply add all the elements(denoted by s in lambda) of the list into the StringJoiner class.

Conclusion

In this quick article, we learned how to use String.join() and StringJoiner class followed by few examples on each of them.
As usual, the code is available on GitHub.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.