Java 8 StringJoiner Example - How to join multiple Strings

The Java 8 has added a new class StringJoiner to join Strings. The java.util.StringJoiner can be used to join any number of arbitrary String, a list of String, or an array of String in Java. You can choose any delimiter to join String e.g. command, pipe, colon or semi-colon. The StringJoiner class also allow you to specify a prefix and suffix while joining two or more String in Java. In order to join Strings, you first create an instance of StringJoiner class. While creating, you provide the delimiter, a String or character, which will be used between Strings while joining them e.g. you can pass comma as a delimiter to create a comma separated String or pipe to create a pipe delimited String. In this article, you will see some examples of StringJoiner to learn how to join String in Java 8.

Some of the readers may be curious that why do you need a new StringJoiner class if you already have StringBuffer and StringBuilder classes to concatenate String, which is nothing but joining. Well, certainly you can use the StringBuffer and StringBuilder class to join String in Java and that's what we do prior to Java 8, StringJoiner provides much cleaner and capable interface to join Strings. You don't need to write logic to start adding comma only after the first element and not to add after the last element, which Java programmers used to do while joining String in Java 6 or JDK 7.

Though StringJoiner is just one of the hidden gems of Java SE 8 release, there is many more day to day useful features which are hidden behind lambda expressions and streams e.g. CompletableFuture. You can see Java SE 8 for Really Impatient by Cay S. Horstmann to learn more about those useful features in quick time.




How to join String by comma in Java 8

Let's see our first example, which will join String by a comma to create a CSV String in Java 8 using the StringJoiner class. In this example, we join arbitrary String e.g. Java, C++, Python, and Ruby to form a comma separated String.

// Creating a StringJoiner with delimiter as comma
StringJoiner joiner = new StringJoiner(",");
joiner.add("Java");
joiner.add("C++");
joiner.add("Python");
joiner.add("Ruby");

String text = joiner.toString();
System.out.println("comma separated String: " + text);

Output
comma separated String: Java,C++,Python,Ruby

You can see that StringJoiner has joined all String you have added to it. You don't need to loop through a list of String anymore. This code may look very similar to StringBuffer but StringJoiner is very different from StringJoiner. You need to explicitly call the append(",") to join String by common here, once you tell StringJoiner about delimiter you are done. No need to call any function or write special logic, except adding String.

You can further shorten the above code in one line because StringJoiner allows fluent API as shown below:

String CSV = new StringJoiner(",").add("Scala").add("Haskell").add("Lisp").toString();
System.out.println("CSV: " + CSV);

Output
CSV: Scala,Haskell,Lisp
You can see that how you can join multiple String in just one line using StringJoiner and fluent API. If you are new to fluent API, then see the classical book Refactoring Improving the Design of Existing Code by Martin Fowler.

How to join String in Java 8 with example


You can also provide prefix and suffix String to StringJoiner which can be used to enclose String e.g. by giving parenthesis as prefix and suffix you can enclose String as shown in our third example below:

String text = new StringJoiner(",", "(", ")")
                  .add("Car Insurance")
                  .add("Health Insurance")
                  .add("Life Insurance").toString();
System.out.println("Insurance: " + text);
         
Output
Insurance: (Car Insurance,Health Insurance,Life Insurance)

You can see in this example, we have enclosed the comma separated String with an opening and closing braces by supplying them as prefix and suffix. One of the useful use cases of this feature is dynamically generating IP address as shown in our fourth example below:

String text = new StringJoiner(".", "[", "]")
                .add("192")
                .add("168")
                .add("2")
                .add("81").toString();
System.out.println("IP address: " + text);

Output
IP address: [192.168.2.81]

You can see the nice and clean IP address generated by supplying opening and closing bracket as prefix and suffix and dot as separator.  To be honest, these are just tip of the iceberg in terms of both StringJoiner and Java 8 features. I suggest you look a comprehensive Java book like Java SE8 for Programmers (3rd Edition) by Paul Deitel and Harvey Dietel, it covers almost everything about Java SE 8. This will allow you to get the full benefit of new API enhancement and Java 8 features in your day to day programming.

Java 8 StringJoiner Examples


That's all about how to use StringJoiner in Java 8 to Join multiple Strings. There is another alternative, you can use String.join() as well to join String. It internally uses StringJoiner for joining String but it's more versatile as it provides another overloaded version of String.join() to join elements from a String array or list of String.


Other Java 8 tutorials you may like


References
Java SE 8 StringJoiner documentation


No comments:

Post a Comment