Java: Join String Array

Java has a string split function, but it does not have a combine/join/unsplit string function. Below is an example modified from the StringUtils library.

package test;

public class Join {
    public static void main(String[] args) {
        String[] toppings = {"Cheese", "Pepperoni", "Black Olives"};
        System.out.println(join(toppings, ";"));
        System.out.println(join(toppings, null));
    }

    public static String join(final String[] array, final String separator) {
        if (array == null) {
            return null;
        }
        final StringBuilder buf = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            if (i > 0) {
                buf.append(separator==null ? "" : separator);
            }
            if (array[i] != null) {
                buf.append(array[i]);
            }
        }
        return buf.toString();
    }
}

Output:

Cheese;Pepperoni;Black Olives
CheesePepperoniBlack Olives

Leave a Reply