Converting ArrayList of Characters to a String?

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.


How about this, Building the list

List<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');

Actual code to get String from List of Character:

String word= new String();
for(char c:charsList){
word= word+ c; 
}
System.out.println(word);

Still learning if there is a misake point out.


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.