323

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

3
  • 1
    What kind of array? Array of strings?
    – adarshr
    Mar 12, 2011 at 15:35
  • 2
    array.toString() ? Be more specific. 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. Mar 12, 2011 at 15:44

14 Answers 14

621

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.

9
  • 14
    Thanks for the explanation on why StringBuilder is superior to += for appending. Jul 16, 2014 at 3:05
  • 2
    May I suggest the "Either use Array.toString()" part. That produces useless output such as "[Ljava.lang.String;@25154f".
    – matteo
    Jan 25, 2015 at 12:33
  • 6
    If you use a += under the covers Java will convert that to using a StringBuilder.
    – Javamann
    Jun 18, 2015 at 16:18
  • 7
    @matteo, You have to use Arrays.toString(yourArray); but i guess You used yourArray.toString();
    – Dzarafata
    Jun 19, 2015 at 7:32
  • 6
    Since java 1.8 you can also use String::join, instead of the for-loop. String.join("", arr); Apr 28, 2016 at 12:23
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
1
  • 1
    minor fix: joinedString = StringUtils.join(new Object[]{"a", "b", "1"}, "-");
    – questborn
    Oct 11, 2012 at 21:22
37

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
  • 10
    But if we were being true to the plot, null would be "he whose name must not be mentioned" :-)
    – Stephen C
    Mar 12, 2011 at 16:12
  • 24
    If you're brave: ;-) Joiner.on(", ").useForNull("Voldemort").join("Harry", null, "Ron", "Hermione");
    – rich
    Mar 12, 2011 at 16:58
  • Using java-8 String.join(", ", "Harry", null, "Ron", "Hermione").replaceAll("null", "Voldermart");
    – Cjo
    Feb 24, 2016 at 11:57
17

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.

0
14

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
  • 23
    StringBuffer is old, use StringBuilder instead which does not have unneeded synchronization for use in one thread.
    – Jason S
    Mar 12, 2011 at 15:44
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
  • 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));
    – neves
    Mar 1, 2016 at 21:55
8

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
  • Then tell us the format you are looking for. Otherwise, we can't guess what you have in mind.
    – Jason S
    Mar 12, 2011 at 15:42
3
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);
    }
}
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

1
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.

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

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

System.out.print(s);
1
  • 3
    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.
    – GhostCat
    Dec 27, 2016 at 15:10
1

Use Apache Commons' StringUtils library's join method.

String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");
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(", "));
-21

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
  • 11
    That's hardly applicable in real world and shows some bad programming practices.
    – Jk1
    Jul 4, 2013 at 20:51
  • 4
    Could be great a gold medal for achieve -50 negatives Aug 29, 2017 at 8:04
  • If a person knows how many elements he has, he mostly will also know what are the elements. So, this answer makes no sense. May 18, 2022 at 6:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.