Lars Andren Lars Andren - 1 year ago 64
Java Question

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

I have a few

s and want to transform each of these into a single
where each element of the original
is separated by a whitespace " ".
A naive first approach is doing it like this

Set<String> set_1;
Set<String> set_2;

StringBuilder builder = new StringBuilder();
for (String str : set_1) {
builder.append(str).append(" ");

this.string_1 = builder.toString();

builder = new StringBuilder();
for (String str : set_2) {
builder.append(str).append(" ");

this.string_2 = builder.toString();

Can anyone think of a faster, prettier or more efficient way to do this?

Answer Source

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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download