41

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
phoenix
  • 3,531
  • 9
  • 30
  • 31

11 Answers11

40

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Vineet Reynolds
  • 76,006
  • 17
  • 150
  • 174
  • What is the advantage of using StringBuilder and than toString method instead of simply use String class? – Line Apr 20 '17 at 12:19
  • 1
    @Line - it is more efficient to use a `StringBuilder`. Appending `N` characters using naive string concatenation is `O(N^2)`. And if you are talking about using `ArrayList.toString()` and filtering, the filtering step is another `O(N)` pass over the string ... compared with single pass approach ^^^. – Stephen C Aug 28 '21 at 00:50
30

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
waggledans
  • 1,231
  • 10
  • 7
2

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.

Shiva
  • 717
  • 9
  • 22
  • 7
    No mistake, but using a StringBuilder is way more efficient than String contatenation – Giuseppe Feb 28 '20 at 10:07
  • 2
    This is an `O(N^2)` solution because each string concatenation is copying the entire string ... so far. Better solutions are `O(N)`. – Stephen C Aug 28 '21 at 01:14
1

You can do it using toString() and RegExp without any loops and streams:

List<Character> list = Arrays.asList('a', 'b', 'c'); String s = list.toString().replaceAll("[,\\s\\[\\]]", "");

1

Using join of a Joiner class:

// create character list and initialize 
List<Character> arr = Arrays.asList('a', 'b', 'c');   
String str = Joiner.on("").join(arr);
System.out.println(str);

Use toString then remove , and spaces

import com.google.common.base.Joiner; 

....
<Character> arr = Arrays.asList('h', 'e', 'l', 'l', 'o'); 
// remove [] and spaces 
String str = arr.toString() 
          .substring(1, 3 * str.size() - 1) //3 bcs of commas ,
          .replaceAll(", ", ""); 
System.out.println(str);

Or by using streams:

import java.util.stream.Collectors; 
...
// using collect and joining() method 
String str =  arr.stream().map(String::valueOf).collect(Collectors.joining()); 
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75
1

Assuming you have a following list:

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

This will yield hello (I am using org.apache.commons.lang.ArrayUtils helper class):

final Character[] charactersArray =
    charsList.toArray(new Character[charsList.size()]);
final char[] charsArray = ArrayUtils.toPrimitive(charactersArray);
System.out.println(String.valueOf(charsArray));
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • why use a third-party library when the standard library will suffice? – mre Jun 12 '11 at 22:04
  • 2
    Is there a standard method that does the same thing as `ArrayUtils#toPrimitive`? I know the problem can be solved with different approaches, I am asking about this specific method which I have chosen to avoid explicit loop. Besides, I can't imagine no `commons-lang` on CLASSPATH nowadays... – Tomasz Nurkiewicz Jun 12 '11 at 22:06
0

a tiny complement to @waggledans 's answer

a) List of Character objects to String :

String str = chars.stream().map(e->e.toString()).collect(Collectors.joining());

which e->e.toString() can be replaced by Object::toString

String str = chars.stream().map(Object::toString).collect(Collectors.joining());
0

Many solutions available. You can iterate over the chars and append to a StringBuilder, then when finished appending, call .toString on the StringBuilder.

Or use something like commons-lang StringUtils.join from the apache commons-lang project.

mkro
  • 1,902
  • 14
  • 15
-1

I consider this an easy and smart way

 // given list containing the chars
 List<Character> arr = Arrays.asList('a', 'b', 'c'); 
 
//convert list to string
 String output = arr.toString().replaceAll("[ ,]","")
                       .substring(1, tmpArr.length()-1);

Explanation:

// convert to string.
String str = arr.toString(); // result is "[a ,b ,c]"

// get rid of the start and the end char i.e '[' & ']'
str = str.substring(1, tmpArr.length()-1);  //result is "a ,b ,c"

// replace <space> and ','
str = str.replaceAll(" ,","") "ABC"
Angelin Nadar
  • 8,944
  • 10
  • 43
  • 53
-2

I would say :

public String arayListToString(ArrayList arrayList){

StringBuffer b = new StringBuffer();

for(String s : arrayList){
   b.append(s);
   b.append(",");
}

return b.toString();
}
Lucas Kauffman
  • 6,789
  • 15
  • 60
  • 86
-3
 private void countChar() throws IOException {
    HashMap hashMap = new HashMap();
    List list = new ArrayList();
    list = "aammit".chars().mapToObj(r -> (char) r).collect(Collectors.toList());
    list.stream().forEach(e -> {
        hashMap.computeIfPresent(e, (K, V) -> (int) V + 1);
        hashMap.computeIfAbsent(e, (V) -> 1);
    });

    System.out.println(hashMap);

}