Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ArrayList of Characters to a String?

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.

like image 290
phoenix Avatar asked Jun 12 '11 21:06

phoenix


People also ask

How do I convert a List to a string in Java?

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.


2 Answers

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.

like image 112
Vineet Reynolds Avatar answered Oct 08 '22 19:10

Vineet Reynolds


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.

like image 41
waggledans Avatar answered Oct 08 '22 19:10

waggledans