Converting ArrayList of Characters to a String?

前端 未结 11 2070
清歌不尽
清歌不尽 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: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();
    }
    

    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.

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

    I would say :

    public String arayListToString(ArrayList arrayList){
    
    StringBuffer b = new StringBuffer();
    
    for(String s : arrayList){
       b.append(s);
       b.append(",");
    }
    
    return b.toString();
    }
    
    0 讨论(0)
  • 2020-12-05 13:45

    Easiest is to loop through.

    List<String> strings = new ArrayList<String>();
    
    // populate strings
    
    StringBuilder builder = new StringBuilder();
    
    for(String string : strings) {
        builder.append(string).append(',');
    }
    
    if(builder.length() > 0) {
    builder.deleteCharAt(builder.length() - 1);
    }
    
    System.out.println(builder);
    
    0 讨论(0)
  • 2020-12-05 13:45
     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);
    
    }
    
    0 讨论(0)
  • 2020-12-05 13:50

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

    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\\[\\]]", "");

    0 讨论(0)
提交回复
热议问题