Joining strings in Java 8 with null safety

Vinicius Mendes
1 min readOct 31, 2019

I have worked with Python for many years, but now I am workig with Java and having a little of experience with inovations in the direction of functional programming brought by Java 8.

In a scenario where I have two Strings wich both can be null, I want to join them by the delimiter “ - “. My first solution was:

Problem is that this solution will break in case any of the Strings is null. So we have to check if it’s null before concatenating. A possible solution would be:

This could solve the problem of null safety, but is too verbose.

With Java 8 streams we can create a much more functional and simple code to achieve the same result. Here it is:

We create a stream with the strings we want to join, then we filter this stream eliminating the null values and collect the remaining items joining by our delimiter “ - “.

That’s it. I will try to post here anytime I solve a problem with elegant solutions like this one.

--

--