Converting ArrayList of Characters to a String?

Viewed 77020

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.

11 Answers

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()); 

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());
 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);

}
Related