During my life so far with Java I found myself often using separated Strings, such as a comma separated String. The reason is simple. Separated Strings are useful in many situations, like persistence prototyping, where you don’t want to add a full blown persistence solution but a small, lightweight file based store to save some values. Or, when you transmit data over the wire and don’t want to use a formal protocol but send just a comma separated String of values. I bet you’ve found yourself implementing a List<String> to comma separated String method at least once ;).

Whenever I used separated Strings, two things bugged me. The first is what I call the “Special Element Handling”. When transforming a collection into a separated String you always have to handle one item uniquely, for example, removing the comma from the last element. The second annoying thing is the formatting. With this I mean the special handling for whitespace or null elements in the collection.

The problem here is that the code that will be created to cover the two issues is everything but clean. Let’s take a look at a simple List to Comma Separated String method.