Convert array of strings into a string in Java

JavaArraysString

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

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

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

Following is an example of Array to String conversion.

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

Solution 9 - Java

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.

Solution 10 - Java

Use Apache Commons' StringUtils library's join method.

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

Solution 11 - Java

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

Solution 12 - Java

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

Solution 13 - Java

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

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

System.out.print(s);

Solution 14 - Java

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]; 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrinceyesurajView Question on Stackoverflow
Solution 1 - JavaMichael BerryView Answer on Stackoverflow
Solution 2 - JavakrockView Answer on Stackoverflow
Solution 3 - JavarichView Answer on Stackoverflow
Solution 4 - JavaMidiparseView Answer on Stackoverflow
Solution 5 - JavaJoeSlavView Answer on Stackoverflow
Solution 6 - JavaSANN3View Answer on Stackoverflow
Solution 7 - JavaadarshrView Answer on Stackoverflow
Solution 8 - Javaparag.raneView Answer on Stackoverflow
Solution 9 - JavaOrtreumView Answer on Stackoverflow
Solution 10 - JavaTanerView Answer on Stackoverflow
Solution 11 - JavalukastymoView Answer on Stackoverflow
Solution 12 - JavaKanagavelu SugumarView Answer on Stackoverflow
Solution 13 - JavaVikramView Answer on Stackoverflow
Solution 14 - JavaJuan DukeView Answer on Stackoverflow