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

Lars Andren picture Lars Andren · Jun 15, 2010 · Viewed 88.6k times · Source

I have a few Set<String>s and want to transform each of these into a single String where each element of the original Set 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

Sean Patrick Floyd picture Sean Patrick Floyd · Jun 15, 2010

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.