Fastest way to put contents of Set to a single String with words separated by a whitespace?

With commons/lang you can do this using StringUtils.join:

String str_1 = StringUtils.join(set_1, " ");

You can’t really beat that for brevity.

Update:

Re-reading this answer, I would prefer the other answer regarding Guava’s Joiner now. In fact, these days I don’t go near apache commons.

Another Update:

Java 8 introduced the method String.join()

String joined = String.join(",", set);

While this isn’t as flexible as the Guava version, it’s handy when you don’t have the Guava library on your classpath.

Leave a Comment