How to implode iterables in Java

The PHP implode function can be quite useful, but no equivalent exist in Java that I know of. Luckily, you can quite easily implement your own.

Implode arrays

This is actually pretty straightforward. Here is what you need to do:

Yeah, I declared this array so that it can contain just any kind of objects. No problem when passing StringBuilder.append(Object), since it will use String.valueOf(Object), returning either the null string if object is null, or the .toString() of the instance.

But arrays in PHP behave more like lists, so why not extend this method to Java Lists?

Implode lists

Using an Iterator is great. It avoids using the .size() to count the elements of the list, and does not require an explicit loop with the .get(int).

Plus, since Iterator applies to all collections, you can extend the method…

Implode collections

Alright, now it works for lists and sets. Just remember the order of elements is not garanteed if you use this method with a set.

[2013/01/16: made methods null safe]

Published by

Cyrille Chopelet

Programming addict, UX philosopher, casual gamer, sci-fi enthusiast, hi-tech dilettante, ... Some people even call me a geek.

"Wit beyond measure is man's greatest treasure." − Rowena Ravenclaw