Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ArrayList <Characters> into a String [duplicate]

Is there a simple way of converting an ArrayList that contains only characters into a string? So say we have

ArrayList<Character> arrayListChar = new ArrayList<Character>();
arrayListChar.add(a);
arrayListChar.add(b);
arrayListChar.add(c);

So the array list contains a, b, and c. Ideally what I'd want to do is turn that into a String "abc".

like image 407
Chris Marker Avatar asked Dec 08 '11 14:12

Chris Marker


4 Answers

Iterator<Character> it = arrayListChar.iterator();
StringBuilder sb = new StringBuilder();

while(it.hasNext()) {
    sb.append(it.next());
}

System.out.println(sb.toString());
like image 142
Jan Vorcak Avatar answered Sep 28 '22 23:09

Jan Vorcak


You could use Apache Common Lang's StringUtils class. It has a join() function like you find in PHP.

Then the code:

StringUtils.join(arrayListChar, "")

would generate:

abc
like image 30
Jonathan M Avatar answered Sep 29 '22 01:09

Jonathan M


    int size = list.size();
    char[] chars = new char[size];
    for (int i = 0; i < size; i++) {
        if (list.size() != size) {
            throw new ConcurrentModificationException();
        }
        chars[i] = list.get(i);
    }
    String s = new String(chars);
like image 36
sudocode Avatar answered Sep 29 '22 00:09

sudocode


Using regex magic:

String result = list.toString().replaceAll(", |\\[|\\]", "");

Get the String representation of the list, which is

[a, b, c]

and then remove the strings "[", "]", and ", ".

like image 43
Tudor Avatar answered Sep 28 '22 23:09

Tudor