Java StringJoiner tutorial

I recently came across the Java StringJoiner class, and I gotta tell you: It is a whole lot better than StringBuilder!

The beauty of the StringJoiner is that you can define a delimiter, which will be added each time you call the StringJoiner#add(String) method. You can also provide a prefix and a suffix, which will be appended placed at the beginning and the end of every String.

To illustrate why it is often a better choice to make use of the StringJoiner, I’ll provide you with an example;

Let’s assume we have an ArrayList of 5 students, which should be printed out like this:
Louis, Chris, Mary, Tom, Mike Litoris.

There’s generally 3 different approaches to solve this problem, using either: String concatenation, a StringBuilder or a StringJoiner.

Building the list with String concatenation

This is almost always a bad idea, because of the nature of Strings; each and every time you concatenate a String, you will automatically create a new object.
Done in a for loop, this can cause performance problems – so I would recommend avoiding String concatenation in for loops unless performance is not an issue.

To build or comma-separated list with String concatenation, we would have to do something like this:

As you can see, this is abit tedious, mainly because of the trailing comma – we don’t want to add the trailing comma to the last element, so we’ll have to constantly check whether we’ve reached the end of the list.

Building the list with StringBuilder

Using a StringBuilder is syntactically very close to using String concatenation. The difference is that we don’t need to use String concatenation, which will enhance performance.

As you can see, we’ve gotten rid of the nasty String concatenation. But still, we can do better.

Building the list with StringJoiner

When using a StringJoiner, we don’t need to keep control of which index we’re currently at – the StringJoiner does that for us. This implies that we can get rid of the regular for loop, and replace it with an enhanced for loop.

As you can see, this is a lot more readable, and not to mention; less error-prone!

If you fancy Java streams, you can also build the list with a short and snappy one-liner;

String out = list.stream().collect(Collectors.joining(", "));

This may all sound trivial, and given our example – it is.
But try to imagine if you had to build a complex SQL query dynamically in Java, without using ORM frameworks.. That task can be solved quite alot easier if you make use of the StringJoiner.

So, what are you waiting for? Go check out the StringJoiner.. 🙂

Quick tip: If you wish to expand your Java skill-set and become an advanced Java developer, I highly recommend you to get yourself a copy of the best-selling Effective Java, by Joshua Bloch!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *