319

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

stefanB
  • 77,323
  • 27
  • 116
  • 141
Princeyesuraj
  • 5,228
  • 6
  • 22
  • 27
  • 1
    What kind of array? Array of strings? – adarshr Mar 12 '11 at 15:35
  • 2
    `array.toString()` ? Be more specific. – Stan Kurilin Mar 12 '11 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. – Dante May Code Mar 12 '11 at 15:44

14 Answers14

613

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.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • 14
    Thanks for the explanation on why StringBuilder is superior to += for appending. – Nicholas Miller Jul 16 '14 at 03:05
  • 2
    May I suggest the "Either use Array.toString()" part. That produces useless output such as "[Ljava.lang.String;@25154f". – matteo Jan 25 '15 at 12:33
  • 6
    If you use a += under the covers Java will convert that to using a StringBuilder. – Javamann Jun 18 '15 at 16:18
  • @Javamann Not if you do the concatenation in a loop (such as here.) – Michael Berry Jun 18 '15 at 18:32
  • 7
    @matteo, You have to use `Arrays.toString(yourArray);` but i guess You used `yourArray.toString();` – Dzarafata Jun 19 '15 at 07:32
  • 1
    Note, that Arrays.toString will produce String like this "[cat, mouse]" – Evgeniy Mishustin Feb 21 '16 at 09:52
  • 6
    Since java ```1.8``` you can also use [```String::join```](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-), instead of the for-loop. ```String.join("", arr);``` – Jorn Vernee Apr 28 '16 at 12:23
  • How is the inverse process done? If I have a string that contains an array of strings, how do I convert it back to an array of strings? [EDIT] There's already an answer to my question here - http://stackoverflow.com/questions/3413586/string-to-string-array-conversion-in-java – Maslor May 11 '16 at 12:24
  • 2
    Android developers can use like String result = TextUtils.join(", ", list); https://stackoverflow.com/questions/33802971/alternative-for-string-join-in-android – Rahul Hawge Aug 28 '17 at 07:05
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
krock
  • 28,904
  • 13
  • 79
  • 85
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.

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

Midiparse
  • 4,701
  • 7
  • 28
  • 48
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();
JoeSlav
  • 4,479
  • 4
  • 31
  • 50
  • 23
    StringBuffer is old, use StringBuilder instead which does not have unneeded synchronization for use in one thread. – Jason S Mar 12 '11 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

SANN3
  • 9,459
  • 6
  • 61
  • 97
  • 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 01 '16 at 21:55
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();
}
adarshr
  • 61,315
  • 23
  • 138
  • 167
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);
    }
}
Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38
parag.rane
  • 139
  • 1
  • 6
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.

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

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

System.out.print(s);
Sid
  • 4,893
  • 14
  • 55
  • 110
Vikram
  • 29
  • 2
  • 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 '16 at 15:10
1

Use Apache Commons' StringUtils library's join method.

String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");
Taner
  • 4,511
  • 3
  • 18
  • 14
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

lukastymo
  • 26,145
  • 14
  • 53
  • 66
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(", "));
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101
-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]; 
Karl Nicoll
  • 16,090
  • 3
  • 51
  • 65
Juan Duke
  • 29
  • 2