4

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".

2

7 Answers 7

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

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

System.out.println(sb.toString());
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1
    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);

Comments

1

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 ", ".

Comments

0

You can override it's toString method and implement the String formatting therein.

Comments

0

Override toString method of ArrayList or the better to extend the ArrayList class so that you may use old ArrayList toString() somewhere else in the code

Comments

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

EDIT - as pointed out already, you should only use code like this if the number of strings to concatenate is small.

1 Comment

String are immutable, you will create a new string for every concatenation. Very bad use of memory. Try using a StringBuilder instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.