[java] Java function for arrays like PHP's join()?

I want to join a String[] with a glue string. Is there a function for this?

This question is related to java arrays join

The answer is


Google guava's library also has this kind of capability. You can see the String[] example also from the API.

As already described in the api, beware of the immutability of the builder methods.

It can accept an array of objects so it'll work in your case. In my previous experience, i tried joining a Stack which is an iterable and it works fine.

Sample from me :

Deque<String> nameStack = new ArrayDeque<>();
nameStack.push("a coder");
nameStack.push("i am");
System.out.println("|" + Joiner.on(' ').skipNulls().join(nameStack) + "|");

prints out : |i am a coder|


java.util.Arrays has an 'asList' method. Together with the java.util.List/ArrayList API this gives you all you need:;

private static String[] join(String[] array1, String[] array2) {

    List<String> list = new ArrayList<String>(Arrays.asList(array1));
    list.addAll(Arrays.asList(array2));
    return list.toArray(new String[0]);
}

A similar alternative

/**
 * @param delimiter 
 * @param inStr
 * @return String
 */
public static String join(String delimiter, String... inStr)
{
    StringBuilder sb = new StringBuilder();
    if (inStr.length > 0)
    {
        sb.append(inStr[0]);
        for (int i = 1; i < inStr.length; i++)
        {
            sb.append(delimiter);                   
            sb.append(inStr[i]);
        }
    }
    return sb.toString();
}

If you are using the Spring Framework then you have the StringUtils class:

import static org.springframework.util.StringUtils.arrayToDelimitedString;

arrayToDelimitedString(new String[] {"A", "B", "C"}, "\n");

I do it this way using a StringBuilder:

public static String join(String[] source, String delimiter) {
    if ((null == source) || (source.length < 1)) {
        return "";
    }

    StringBuilder stringbuilder = new StringBuilder();
    for (String s : source) {
        stringbuilder.append(s + delimiter);
    }
    return stringbuilder.toString();
} // join((String[], String)

To get "str1, str2" from "str1", "str2", "" :

Stream.of("str1", "str2", "").filter(str -> !str.isEmpty()).collect(Collectors.joining(", ")); 

Also you can add extra null-check


If you were looking for what to use in android, it is:

String android.text.TextUtils.join(CharSequence delimiter, Object[] tokens)

for example:

String joined = TextUtils.join(";", MyStringArray);

There is simple shorthand technique I use most of the times..

String op = new String;
for (int i : is) 
{
    op += candidatesArr[i-1]+",";
}
op = op.substring(0, op.length()-1);

In Java 8 you can use

1) Stream API :

String[] a = new String[] {"a", "b", "c"};
String result = Arrays.stream(a).collect(Collectors.joining(", "));

2) new String.join method: https://stackoverflow.com/a/21756398/466677

3) java.util.StringJoiner class: http://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html


This is how I do it.

private String join(String[] input, String delimiter)
{
    StringBuilder sb = new StringBuilder();
    for(String value : input)
    {
        sb.append(value);
        sb.append(delimiter);
    }
    int length = sb.length();
    if(length > 0)
    {
        // Remove the extra delimiter
        sb.setLength(length - delimiter.length());
    }
    return sb.toString();
}

Do you like my 3-lines way using only String class's methods?

static String join(String glue, String[] array) {
    String line = "";
    for (String s : array) line += s + glue;
    return (array.length == 0) ? line : line.substring(0, line.length() - glue.length());
}

In case you're using Functional Java library and for some reason can't use Streams from Java 8 (which might be the case when using Android + Retrolambda plugin), here is a functional solution for you:

String joinWithSeparator(List<String> items, String separator) {
    return items
            .bind(id -> list(separator, id))
            .drop(1)
            .foldLeft(
                    (result, item) -> result + item,
                    ""
            );
}

Note that it's not the most efficient approach, but it does work good for small lists.


A little mod instead of using substring():

//join(String array,delimiter)
public static String join(String r[],String d)
{
        if (r.length == 0) return "";
        StringBuilder sb = new StringBuilder();
        int i;
        for(i=0;i<r.length-1;i++){
            sb.append(r[i]);
            sb.append(d);
        }
        sb.append(r[i]);
        return sb.toString();
}

As with many questions lately, Java 8 to the rescue:


Java 8 added a new static method to java.lang.String which does exactly what you want:

public static String join(CharSequence delimeter, CharSequence... elements);

Using it:

String s = String.join(", ", new String[] {"Hello", "World", "!"});

Results in:

"Hello, World, !"

Not in core, no. A search for "java array join string glue" will give you some code snippets on how to achieve this though.

e.g.

public static String join(Collection s, String delimiter) {
    StringBuffer buffer = new StringBuffer();
    Iterator iter = s.iterator();
    while (iter.hasNext()) {
        buffer.append(iter.next());
        if (iter.hasNext()) {
            buffer.append(delimiter);
        }
    }
    return buffer.toString();
}

My spin.

public static String join(Object[] objects, String delimiter) {
  if (objects.length == 0) {
    return "";
  }
  int capacityGuess = (objects.length * objects[0].toString().length())
      + ((objects.length - 1) * delimiter.length());
  StringBuilder ret = new StringBuilder(capacityGuess);
  ret.append(objects[0]);
  for (int i = 1; i < objects.length; i++) {
    ret.append(delimiter);
    ret.append(objects[i]);
  }
  return ret.toString();
}

public static String join(Object... objects) {
  return join(objects, "");
}

If you've landed here looking for a quick array-to-string conversion, try Arrays.toString().

Creates a String representation of the Object[] passed. The result is surrounded by brackets ("[]"), each element is converted to a String via the String.valueOf(Object) and separated by ", ". If the array is null, then "null" is returned.


Given:

String[] a = new String[] { "Hello", "World", "!" };

Then as an alternative to coobird's answer, where the glue is ", ":

Arrays.asList(a).toString().replaceAll("^\\[|\\]$", "")

Or to concatenate with a different string, such as " &amp; ".

Arrays.asList(a).toString().replaceAll(", ", " &amp; ").replaceAll("^\\[|\\]$", "")

However... this one ONLY works if you know that the values in the array or list DO NOT contain the character string ", ".


Nothing built-in that I know of.

Apache Commons Lang has a class called StringUtils which contains many join functions.


You could easily write such a function in about ten lines of code:

String combine(String[] s, String glue)
{
  int k = s.length;
  if ( k == 0 )
  {
    return null;
  }
  StringBuilder out = new StringBuilder();
  out.append( s[0] );
  for ( int x=1; x < k; ++x )
  {
    out.append(glue).append(s[x]);
  }
  return out.toString();
}

Just for the "I've the shortest one" challenge, here are mines ;)

Iterative:

public static String join(String s, Object... a) {
    StringBuilder o = new StringBuilder();
    for (Iterator<Object> i = Arrays.asList(a).iterator(); i.hasNext();)
        o.append(i.next()).append(i.hasNext() ? s : "");
    return o.toString();
}

Recursive:

public static String join(String s, Object... a) {
    return a.length == 0 ? "" : a[0] + (a.length == 1 ? "" : s + join(s, Arrays.copyOfRange(a, 1, a.length)));
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to join

Pandas Merging 101 pandas: merge (join) two data frames on multiple columns How to use the COLLATE in a JOIN in SQL Server? How to join multiple collections with $lookup in mongodb How to join on multiple columns in Pyspark? Pandas join issue: columns overlap but no suffix specified MySQL select rows where left join is null How to return rows from left table not found in right table? Why do multiple-table joins produce duplicate rows? pandas three-way joining multiple dataframes on columns