How to convert an ArrayList<Character>
to a String
in Java?
The List.toString
method returns it as [a,b,c]
string - I want to get rid of the brackets (etcetera) and store it as abc
.
We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.
You can iterate through the list and create the string.
String getStringRepresentation(ArrayList<Character> list) { StringBuilder builder = new StringBuilder(list.size()); for(Character ch: list) { builder.append(ch); } return builder.toString(); }
Setting the capacity of the StringBuilder
to the list size is an important optimization. If you don't do this, some of the append
calls may trigger an internal resize of the builder.
As an aside, toString()
returns a human-readable format of the ArrayList's contents. It is not worth the time to filter out the unnecessary characters from it. It's implementation could change tomorrow, and you will have to rewrite your filtering code.
Here a possible one-line solution using Java8 streams.
a) List of Character objects to String :
String str = chars.stream() .map(e->e.toString()) .reduce((acc, e) -> acc + e) .get();
b) array of chars (char[] chars)
String str = Stream.of(chars) .map(e->new String(e)) .reduce((acc, e) -> acc + e) .get();
UPDATE (following comment below):
a) List of Character objects to String :
String str = chars.stream() .map(e->e.toString()) .collect(Collectors.joining());
b) array of chars (char[] chars)
String str = Stream.of(chars) .map(e->new String(e)) .collect(Collectors.joining());
Note that the map(e->e.toString())
step in the above solutions will create a temporary string for each character in the list. The strings immediately become garbage. So, if the performance of the conversion is a relevant concern, you should consider using the StringBuilder
approach instead.
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