How to join Array to String (Java) in one line?

6.5k Views Asked by At

Let's assume there is an array:

String[] myArray = new String[]{"slim cat", "fat cat", "extremely fat cat"};

Now I want to transform this array into a String joined with "&". So that the output becomes:

slim cat&fat cat&extremely fat cat

I am trying to keep my code shorter and clean, without the need to manually type a for loop.

I would like to have a short solution, like we use in reverse way with someString.split();.

How can I achieve this?

5

There are 5 best solutions below

2
On BEST ANSWER

Using Java 8, String.join(CharSequence delimiter, CharSequence... elements):

String result = String.join("&", myArray);

Using Java 7 or earlier, you either need a loop or recursion.

2
On

Edit: Why without a for loop?

Use a StringBuilder

StringBuilder builder = new StringBuilder();
builder.append( myArray.remove(0));

for( String s : myArray) {
    builder.append( "&");
    builder.append( s);
}

String result = builder.toString();
0
On

Use Guava's Joiner or Java 8 StringJoiner.

0
On

There's no way to do this job without some sort of iteration over the array. Even languages that offer some form of a join() function (which do not include Java < version 8) must internally perform some sort of iteration.

About the simplest way to do it in Java <= 7 is this:

StringBuilder sb = new StringBuilder();
String result;

for (String s : myArray) {
    sb.append(s).append('&');
}
sb.deleteCharAt(sb.length() - 1);

result = sb.toString();
1
On

Use Apache Commons Lang, StringUtils.join(Object[] array, char separator).

Example:

String result = StringUtils.join(myArray, '&');

This library is also compatible with Java 7 and earlier. Plus, it has a lot of overloaded methods.