333

I want the Java code for converting an array of strings into an string.

2
  • 3
    array.toString() ? Be more specific. Commented Mar 12, 2011 at 15:36
  • 1
    @Princeyesuraj, the official answer is provided by adarshr. If you want own separator, you can try JoeSlav's answer, and if no thread problem, you can use StringBuilder instead of StringBuffer for effiency. krock's answer is good, but a little bit overkilling in my opinion. Commented Mar 12, 2011 at 15:44

14 Answers 14

641

Java 8+

Use String.join():

String str = String.join(",", arr);

Note that arr can also be any Iterable (such as a list), not just an array.

If you have a Stream, you can use the joining collector:

Stream.of("a", "b", "c")
      .collect(Collectors.joining(","))

Legacy (Java 7 and earlier)

StringBuilder builder = new StringBuilder();
for(String s : arr) {
    builder.append(s);
}
String str = builder.toString();

Alternatively, if you just want a "debug-style" dump of an array:

String str = Arrays.toString(arr);

Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer.

Android

Use TextUtils.join():

String str = TextUtils.join(",", arr);

General notes

You can modify all the above examples depending on what characters, if any, you want in between strings.

DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks for the explanation on why StringBuilder is superior to += for appending.
May I suggest the "Either use Array.toString()" part. That produces useless output such as "[Ljava.lang.String;@25154f".
If you use a += under the covers Java will convert that to using a StringBuilder.
@matteo, You have to use Arrays.toString(yourArray); but i guess You used yourArray.toString();
Since java 1.8 you can also use String::join, instead of the for-loop. String.join("", arr);
|
106

Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:

String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);

Produces:

a-b-1

Comments

38

I like using Google's Guava Joiner for this, e.g.:

Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");

would produce the same String as:

new String("Harry, Ron, Hermione");

ETA: Java 8 has similar support now:

String.join(", ", "Harry", "Ron", "Hermione");

Can't see support for skipping null values, but that's easily worked around.

3 Comments

But if we were being true to the plot, null would be "he whose name must not be mentioned" :-)
If you're brave: ;-) Joiner.on(", ").useForNull("Voldemort").join("Harry", null, "Ron", "Hermione");
Using java-8 String.join(", ", "Harry", null, "Ron", "Hermione").replaceAll("null", "Voldermart");
18

From Java 8, the simplest way I think is:

    String[] array = { "cat", "mouse" };
    String delimiter = "";
    String result = String.join(delimiter, array);

This way you can choose an arbitrary delimiter.

Comments

13

You could do this, given an array a of primitive type:

StringBuffer result = new StringBuffer();
for (int i = 0; i < a.length; i++) {
   result.append( a[i] );
   //result.append( optional separator );
}
String mynewstring = result.toString();

1 Comment

StringBuffer is old, use StringBuilder instead which does not have unneeded synchronization for use in one thread.
10

Try the Arrays.deepToString method.

Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings

1 Comment

If you don't need a lot of control, I believe this is the simplest solution since you don't need a third party lib. Here is an example: System.out.println(Arrays.deepToString(args));
7

Try the Arrays.toString overloaded methods.

Or else, try this below generic implementation:

public static void main(String... args) throws Exception {

    String[] array = {"ABC", "XYZ", "PQR"};

    System.out.println(new Test().join(array, ", "));
}

public <T> String join(T[] array, String cement) {
    StringBuilder builder = new StringBuilder();

    if(array == null || array.length == 0) {
        return null;
    }

    for (T t : array) {
        builder.append(t).append(cement);
    }

    builder.delete(builder.length() - cement.length(), builder.length());

    return builder.toString();
}

1 Comment

Then tell us the format you are looking for. Otherwise, we can't guess what you have in mind.
2
public class ArrayToString
{   
    public static void main(String[] args)
    {
        String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};
        
        String newString = Arrays.toString(strArray);
        
        newString = newString.substring(1, newString.length()-1);

        System.out.println("New New String: " + newString);
    }
}

Comments

1

You want code which produce string from arrayList,

Iterate through all elements in list and add it to your String result

you can do this in 2 ways: using String as result or StringBuffer/StringBuilder.

Example:

String result = "";
for (String s : list) {
    result += s;
}

...but this isn't good practice because of performance reason. Better is using StringBuffer (threads safe) or StringBuilder which are more appropriate to adding Strings

Comments

1

Use Apache Commons' StringUtils library's join method.

String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");

Comments

0
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';

String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s

result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s

result = String.join("", strings);
//Java 8 .join: 3ms

Public String join(String delimiter, String[] s)
{
    int ls = s.length;
    switch (ls)
    {
        case 0: return "";
        case 1: return s[0];
        case 2: return s[0].concat(delimiter).concat(s[1]);
        default:
            int l1 = ls / 2;
            String[] s1 = Arrays.copyOfRange(s, 0, l1); 
            String[] s2 = Arrays.copyOfRange(s, l1, ls); 
            return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
    }
}
result = join("", strings);
// Divide&Conquer join: 7ms

If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.

Comments

0
String array[]={"one","two"};
String s="";

for(int i=0;i<array.length;i++)
{
  s=s+array[i];
}

System.out.print(s);

1 Comment

Your answer is basically the same as smas; just a bit more complicated; thus sure not "the most easy" one. And besides, Arrays.toString() is even easier.
0

When we use stream we do have more flexibility, like
map --> convert any array object to toString
filter --> remove when it is empty
join --> Adding joining character

    //Deduplicate the comma character in the input string
    String[] splits = input.split("\\s*,\\s*");
    return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors.joining(", "));

Comments

-22

If you know how much elements the array has, a simple way is doing this:

String appendedString = "" + array[0] + "" + array[1] + "" + array[2] + "" + array[3]; 

3 Comments

That's hardly applicable in real world and shows some bad programming practices.
Could be great a gold medal for achieve -50 negatives
If a person knows how many elements he has, he mostly will also know what are the elements. So, this answer makes no sense.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.