Core Java

StringJoiner vs String.join in Java 8 with Examples

Joining multiple String literals or object into one is a common programming requirement and you will often find situations where you need to convert a list of String or a Collection of String into a CSV String for your application. For a long time, JDK API has no way to join multiple String literals or objects together, which forces programmers to write hacks like looping through all String objects and manually joining them using String concatenation to create the final, joined String. Even though this approach worked, it was filled with errors and hacks like you need to be careful not to add delimiter before the first element and after the last element, which often caused issues, particularly in case of beginners and junior Java developers.

But the bigger problem with that approach was that everyone needs to re-invent the wheel. Since it was a very common requirement you will find many programmers writing the same routines and making the same mistakes and often ending in StackOverflow to solve their problems.  Thankfully Java 8 solved this problem once for all.

The JDK 8 API provides a couple of more ways to join Strings like you can join String by using the StringJoiner class or you can join the String by calling the  String.join() method.

In this article, we’ll explore both these ways to join string and understand what is the difference between them, pros and cons of each approach and when to use StringJoiner and when String.join() is a better option.

Joining String using StringJoiner in Java 8

The JDK 8 API has added a new class called java.util.StringJoiner which allows you to join more than one String using a specified delimiter or joiner. For example, you can join multiple strings separated by comma
(,) to create a CSV String, Or even better, you can create a full path for a directory in Linux by joining String using forward slash “/” as explained by Cay. S. Horstmann in the Java SE 9 for the Impatient, my favorite book to learn Java.

Here is an example:

StringJoiner joiner = new StringJoiner("/");
joiner.add("usr");
joiner.add("local");
joiner.add("bin");

This will give you a string like “usr/local/bin” which you can pass it to any program.  You can further add a “/” using prefix if you want to use it as an absolute path or use it like this if you need a relative path.

One more advantage of StringJoiner is the fluent API it offers which means you can write code in one line. For example, the above code can be re-written as following using fluent methods of StringJoiner:

String result= new StringJoiner("/").add("usr").add("local").add("bin");

This will print:

"usr/local/bin"

Joining String using join() method in Java 8

The problem with StringJoiner is that you need to know that there is a StringJoiner class which is not too bad but what if you can directly join the String from much popular java.lang.String class itself? Well, that’s what Java designers thought and they have added a static join() method to join the String right from the String class itself.

here is an example of using String.join() method to join multiple String literals in Java:

String colonSeparatedValue = String.join(":", "abc", "bcd", "def");
  System.out.println("colon separated String : " + colonSeparatedValue);

This will print the following String:

colon separated String : abc:bcd:def

Which is quite good because now you don’t need to worry about
not adding delimeter at the start or removing it from the end, one of the common problems you face while manually joining multiple String together in a loop separated by a delimiter as shown earlier in my example of generating CSV String in Java.

Another advantage of String.join() method is that you can now directly convert a list of String into a CSV String in Java, without writing any manual code, here is an example of how to do it.

List mylist = Arrays.asList("London", "Paris", "NewYork");
        String joined = String.join("||", mylist);
        System.out.println("Joined String : " + joined);

This will print the following String:

Joined String : London||Paris||NewYork

That’s cool, isn’t it? Now you are free from converting a list of String or set of String to a CSV String manually in Java. It’s also worth noting that String.join() internally uses StringJoiner class for joining String literals.

2 Ways to Join String in Java 8

Here are 2 ways to join String in Java 8, the first example uses
StringJoiner class while the second example uses String.join() method, a static utility method added on java.lang.String on JDK 8.

package test;
 
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
 
/**
 * Java program to show how to join String in Java 8.
 * There are two ways to do that in Java 8, by using StringJoiner or
 * by using join() method of String class.
 * @author Javin
 */
 
public class Test {
 
    public static void main(String args[]) {
 
        // StringJoiner can join multiple String using any delimiter
        // Let's create a CSV String by joining Stirng using comma
        StringJoiner joiner = new StringJoiner(",");
        joiner.add("one");
        joiner.add("two");
        joiner.add("three");
 
        System.out.println("Comma separated String : " + joiner.toString());
 
        // You can combine all three lines into one because
        // StringJoiner provides a fluent interface
        StringJoiner delimitedString = new StringJoiner("|").add("id").add("name"); 
        System.out.println("Pipe delimited String : " + delimitedString);
 
        // 2nd Example: You can also join String by String.join() method
        // By far, this is the most convenient method to join Strings
        // in Java.    
 
        String csv = String.join(":", "abc", "bcd", "def");
        System.out.println("colon separated String : " + csv);
 
 
        // You can even use String.join() method to join contents of
        // ArrayList, Array, LinkedList or any collection, actually
        // any container which implements Iterable interface
        List mylist = Arrays.asList("London", "Paris", "NewYork");
        String joined = String.join("||", mylist);
        System.out.println("Joined String : " + joined);  
 
    }
 
}
 
Output
Comma separated String : one,two,three
Pipe delimited String : id|name
colon separated String : abc:bcd:def
Joined String : London||Paris||NewYork

That’s all about 2 ways to join String in Java 8. Now, you can finally join the String in Java 8 without using a third party library and you also have options to use the class which makes sense for you. In general, join() method of String class is more convenient because you can directly call and pass both delimeter and individual String objects which need to be joined.

I mean, you don’t need to create another object like StringJoiner. It also allows you to join String from a Collection class like ArrayList or LinkedList, which means you can create a comma-separated String from an ArrayList of String, how cool is that?

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any questions or suggestions then please drop a comment.

Published on Java Code Geeks with permission by Javin Paul, partner at our JCG program. See the original article here: StringJoiner vs String.join in Java 8 with Examples

Opinions expressed by Java Code Geeks contributors are their own.

Javin Paul

I have been working in Java, FIX Tutorial and Tibco RV messaging technology from past 7 years. I am interested in writing and meeting people, reading and learning about new subjects.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button