Perl-style join() function in Java

by

This comes up pretty frequently and seems like an odd omission from the standard library, particularly given that String now has split(). Most attempts are a little untidy, here’s the simplest expression of it that I could come up with:

public static String join(String separator, Object... items)
  {
  StringBuffer result = new StringBuffer();

  for (Object item : items)
    {
    if (result.length() > 0)
      result.append(separator);

    result.append(item);
    }

  return result.toString();
  }

There is a theoretical performance improvement to be had in not repeatedly calling length() but without an actual bottleneck situation to solve, I’d err on the side of simplicity.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: