Converting ArrayList of Characters to a String?

前端 未结 11 2148
清歌不尽
清歌不尽 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 14:01

    Using join of a Joiner class:

    // create character list and initialize 
    List 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; 
    
    ....
     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()); 
    

提交回复
热议问题