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".
Iterator<Character> it = arrayListChar.iterator(); StringBuilder sb = new StringBuilder(); while(it.hasNext()) { sb.append(it.next()); } System.out.println(sb.toString());
You can use the Apache Common Lang's class> StringUtils. It has a function join(), as you find in PHP.
join()
Then the code:
StringUtils.join(arrayListChar, "")
will generate:
abc
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);
toString String.
toString
String
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
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.
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 ", ".
"[", "]", and ", "