Tip of the day #19

Use the joining collector and stop to write loops to concatenate strings.

What is it?

The joining collector is a new collector that was introduced in Java 8. It is a special collector that is used to concatenate strings.

We have 3 different ways to use it:

1 - join all strings without any delimiter

// 1
String result = Stream.of("a", "b", "c")
    .collect(Collectors.joining());
// abc

2 - join all strings with a delimiter

// 2
String result = Stream.of("a", "b", "c")
    .collect(Collectors.joining(", "));
// a, b, c

3 - join all strings with a delimiter and a prefix and suffix

// 3
String result = Stream.of("a", "b", "c")
    .collect(Collectors.joining(", ", "[", "]"));
// [a, b, c]

Important to note that all then join the strings in the same order that they are in the stream.

They are also null-safe, so if you have a null value in the stream, it will not throws an exception, but will add null as String in your final output.

String result = Stream.of("a", null, "b", "c")
    .collect(Collectors.joining(", "));
// a, null, b, c

Why should I use it?

It is a very simple and easy way to concatenate strings. You do not need to create a StringBuilder, append all the strings and then convert it to string. It is also null-safe, so you do not need to worry about null values in the stream.

When should I use it?

After today, do not use more StringBuilders to concatenate strings anymore, use the joining collector instead.

How to

Take a look in repo-tip-19 to see a real example of today’s tip.

Because @QuarkusTest and @ParameterizedTest has some issues, I created a new repo to show the example using Spring Boot. Here we can use records. repo-tip-19-spring