Lab Notes

Things I want to remember how to do.

Complicated String Joins

April 4, 2016

So if you have not been under a rock and have used Java 8, you are surely aware of the new String.join() method and the Collectors.joining() method to concatenate arrays or streams of Strings. Sometimes however, a simple concatenation with a delimiter is not quite up to the job.

Consider the following method for example:

Here our plans for a simple invocation of Collectors.joining() is complicated by the intermediate String literals and the particular format desired for the string representation of the entry.

At first blush you might attempt to change this to functional style using something like this:

If you are an old salt at Java however, I'm sure your hair is standing on end considering all those temporary String objects being created. Fortunately, using Stream.of() and Stream.flatMap() there is another way:

If you want to play around with this code, it is available on GitHub at