Convert Array of Strings into a String in Java

Convert array of strings into a string in 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.

string to string array conversion in java

To start you off on your assignment, String.split splits strings on a regular expression and this expression may be an empty string:

String[] ary = "abc".split("");

Yields the array:

(java.lang.String[]) [, a, b, c]

Getting rid of the empty 1st entry is left as an exercise for the reader :-)

Note: In Java 8, the empty first element is no longer included.

Best way to convert an ArrayList to a string

Java 8 introduces a String.join(separator, list) method; see Vitalii Federenko's answer.

Before Java 8, using a loop to iterate over the ArrayList was the only option:

DO NOT use this code, continue reading to the bottom of this answer to see why it is not desirable, and which code should be used instead:

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

String listString = "";

for (String s : list)
{
listString += s + "\t";
}

System.out.println(listString);

In fact, a string concatenation is going to be just fine, as the javac compiler will optimize the string concatenation as a series of append operations on a StringBuilder anyway. Here's a part of the disassembly of the bytecode from the for loop from the above program:

   61:  new #13; //class java/lang/StringBuilder
64: dup
65: invokespecial #14; //Method java/lang/StringBuilder."<init>":()V
68: aload_2
69: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
72: aload 4
74: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
77: ldc #16; //String \t
79: invokevirtual #15; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
82: invokevirtual #17; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;

As can be seen, the compiler optimizes that loop by using a StringBuilder, so performance shouldn't be a big concern.

(OK, on second glance, the StringBuilder is being instantiated on each iteration of the loop, so it may not be the most efficient bytecode. Instantiating and using an explicit StringBuilder would probably yield better performance.)

In fact, I think that having any sort of output (be it to disk or to the screen) will be at least an order of a magnitude slower than having to worry about the performance of string concatenations.

Edit: As pointed out in the comments, the above compiler optimization is indeed creating a new instance of StringBuilder on each iteration. (Which I have noted previously.)

The most optimized technique to use will be the response by Paul Tomblin, as it only instantiates a single StringBuilder object outside of the for loop.

Rewriting to the above code to:

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

StringBuilder sb = new StringBuilder();
for (String s : list)
{
sb.append(s);
sb.append("\t");
}

System.out.println(sb.toString());

Will only instantiate the StringBuilder once outside of the loop, and only make the two calls to the append method inside the loop, as evidenced in this bytecode (which shows the instantiation of StringBuilder and the loop):

   // Instantiation of the StringBuilder outside loop:
33: new #8; //class java/lang/StringBuilder
36: dup
37: invokespecial #9; //Method java/lang/StringBuilder."<init>":()V
40: astore_2

// [snip a few lines for initializing the loop]
// Loading the StringBuilder inside the loop, then append:
66: aload_2
67: aload 4
69: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
72: pop
73: aload_2
74: ldc #15; //String \t
76: invokevirtual #14; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
79: pop

So, indeed the hand optimization should be better performing, as the inside of the for loop is shorter and there is no need to instantiate a StringBuilder on each iteration.

Converting 'ArrayListString to 'String[]' in Java

List<String> list = ..;
String[] array = list.toArray(new String[0]);

For example:

List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);

The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

Convert ArrayListString to String[] array

Use like this.

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

for(String s : stockArr)
System.out.println(s);

Convert String array to ArrayList

Use this code for that,

import java.util.Arrays;  
import java.util.List;
import java.util.ArrayList;

public class StringArrayTest {

public static void main(String[] args) {
String[] words = {"ace", "boom", "crew", "dog", "eon"};

List<String> wordList = Arrays.asList(words);

for (String e : wordList) {
System.out.println(e);
}
}
}

converting an array of strings into a simple string and vice-versa in c#

Try like this

join

var str = string.Join(",", array);

array

var strArr = str.Split(',');

DOTNETFIDDLE

Convert array of Strings to list of Integers?

You only need to stream once.

Instead of using int Integer::parseInt(String s), you should use Integer Integer::valueOf(String s), so you don't have to call boxed() or rely on auto-boxing.

Then use collect(Collectors.toList()) directly, instead of creating intermediate array first.

List<Integer> allAnswerList = Arrays.stream(allAnswers)    // stream of String
.map(Integer::valueOf) // stream of Integer
.collect(Collectors.toList());


Related Topics



Leave a reply



Submit