Convert ArrayList <Characters> to string

Is there an easy way to convert an ArrayList containing only characters to a string? So let's say

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

So, the list of arrays contains a, b and c. Ideally, what I would like to do is turn this into the string "abc".

+5
source share
7 answers
Iterator<Character> it = arrayListChar.iterator();
StringBuilder sb = new StringBuilder();

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

System.out.println(sb.toString());
+3
source

You can use the Apache Common Lang's class> StringUtils. It has a function join(), as you find in PHP.

Then the code:

StringUtils.join(arrayListChar, "")

will generate:

abc
+3
source
    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);
+1

toString String.

0

Override the toString method for ArrayList or better extend the ArrayList class so you can use the old ArrayList toString () somewhere else in the code

0
source
    String s = "";
    for(Character i : arrayListChar)
           s += i;

EDIT - as already indicated, you should use only such code if the number of lines for concatenation is small.

0
source

Using regex magic:

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

Get a string representation of a list that

[a, b, c]

and then delete the lines "[", "]", and ", ".

0
source

All Articles