A method to reverse effect of java String.split()? [duplicate]

I am looking for a method to combine an array of strings into a delimited String. An opposite to split().

Wanted to ask the forum before I try writing my own (since the JDK has everything)


Solution 1:

There's no method in the JDK for this that I'm aware of. Apache Commons Lang has various overloaded join() methods in the StringUtils class that do what you want.

Solution 2:

There has been an open feature request since at least 2009. The long and short of it is that it will part of the functionality of JDK 8's java.util.StringJoiner class. http://download.java.net/lambda/b81/docs/api/java/util/StringJoiner.html

Here is the Oracle issue if you are interested. http://bugs.sun.com/view_bug.do?bug_id=5015163

Here is an example of the new JDK 8 StringJoiner on an array of String

String[] a = new String[]{"first","second","third"};
StringJoiner sj = new StringJoiner(",");
for(String s:a) sj.add(s);
System.out.println(sj); //first,second,third

A utility method in String makes this even simpler:

String s = String.join(",", stringArray);

Solution 3:

You can sneak this functionality out of the Arrays utility package.

import java.util.Arrays;
...
    String delim = ":",
            csv_record = "Field0:Field1:Field2",
            fields[] = csv_record.split(delim);

    String rebuilt_record = Arrays.toString(fields)
            .replace(", ", delim)
            .replaceAll("[\\[\\]]", "");

Solution 4:

I got the following example here

/*
7) Join Strings using separator >>>AB$#$CD$#$EF

 */

import org.apache.commons.lang.StringUtils;

public class StringUtilsTrial {
  public static void main(String[] args) {

    // Join all Strings in the Array into a Single String, separated by $#$
    System.out.println("7) Join Strings using separator >>>"
        + StringUtils.join(new String[] { "AB", "CD", "EF" }, "$#$"));
  }
}

Solution 5:

Google also provides a joiner class in their Google Collections library:

Joiner API

Google Collections