5

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

Chris Marker
  • 219
  • 1
  • 4
  • 9
  • 1
    Possible duplicate of question: http://stackoverflow.com/q/6324826/601409 – EkcenierK Dec 08 '11 at 14:20
  • even better answers were provided here: http://stackoverflow.com/questions/523871/best-way-to-concatenate-list-of-string-objects It's about concatenating list of Strings, but close. – jFrenetic Dec 08 '11 at 14:24

7 Answers7

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

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

System.out.println(sb.toString());
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90
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
Jonathan M
  • 17,145
  • 9
  • 58
  • 91
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);
ewan.chalmers
  • 16,145
  • 43
  • 60
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 ", ".

Tudor
  • 61,523
  • 12
  • 102
  • 142
0

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

mre
  • 43,520
  • 33
  • 120
  • 170
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

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.

Wozza
  • 622
  • 2
  • 9
  • 21
  • String are immutable, you will create a new string for every concatenation. Very bad use of memory. Try using a StringBuilder instead. – Tudor Dec 08 '11 at 14:26