I want the Java code for converting an array of strings into an string.
So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.
Convert Array to String. Sometimes we need to convert an array of strings or integers into a string, but unfortunately, there is no direct method to perform this conversion. The default implementation of the toString() method on an array returns something like Ljava. lang.
To convert a JavaScript array into a string, you can use the built-in Array method called toString . Keep in mind that the toString method can't be used on an array of objects because it will return [object Object] instead of the actual values.
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(","))
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
.
Use TextUtils.join()
:
String str = TextUtils.join(",", arr);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With