Ernestas Gruodis
Ernestas Gruodis

Reputation: 8787

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

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?

Upvotes: 5

Views: 9400

Answers (5)

josivan
josivan

Reputation: 2073

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.

Upvotes: 1

Sergii Lagutin
Sergii Lagutin

Reputation: 10681

Use Guava's Joiner or Java 8 StringJoiner.

Upvotes: 3

ajb
ajb

Reputation: 31699

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.

Upvotes: 21

John Bollinger
John Bollinger

Reputation: 180998

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();

Upvotes: 0

Zerp
Zerp

Reputation: 892

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();

Upvotes: 2

Related Questions