Converting ArrayList of Characters to a String?

前端 未结 11 2071
清歌不尽
清歌不尽 2020-12-05 13:39

How to convert an ArrayList to a String in Java? The toString method returns it as [a,b,c] string - I wa

相关标签:
11条回答
  • 2020-12-05 13:55

    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.

    0 讨论(0)
  • 2020-12-05 13:55

    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 讨论(0)
  • 2020-12-05 13:57

    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());
    
    0 讨论(0)
  • 2020-12-05 14:00

    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.

    0 讨论(0)
  • 2020-12-05 14:01

    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()); 
    
    0 讨论(0)
提交回复
热议问题