How to convert an ArrayList
to a String
in Java?
The toString
method returns it as [a,b,c]
string - I wa
You can iterate through the list and create the string.
String getStringRepresentation(ArrayList<Character> list)
{
StringBuilder builder = new StringBuilder(list.size());
for(Character ch: list)
{
builder.append(ch);
}
return builder.toString();
}
As an aside, toString()
returns a human-readable format of the ArrayList's contents. It is not worth the time to filter out the unnecessary characters from it. It's implementation could change tomorrow, and you will have to rewrite your filtering code.
I would say :
public String arayListToString(ArrayList arrayList){
StringBuffer b = new StringBuffer();
for(String s : arrayList){
b.append(s);
b.append(",");
}
return b.toString();
}
Easiest is to loop through.
List<String> strings = new ArrayList<String>();
// populate strings
StringBuilder builder = new StringBuilder();
for(String string : strings) {
builder.append(string).append(',');
}
if(builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
System.out.println(builder);
private void countChar() throws IOException {
HashMap hashMap = new HashMap();
List list = new ArrayList();
list = "aammit".chars().mapToObj(r -> (char) r).collect(Collectors.toList());
list.stream().forEach(e -> {
hashMap.computeIfPresent(e, (K, V) -> (int) V + 1);
hashMap.computeIfAbsent(e, (V) -> 1);
});
System.out.println(hashMap);
}
Assuming you have a following list:
final ArrayList<Character> charsList = new ArrayList<Character>();
charsList.add('h');
charsList.add('e');
charsList.add('l');
charsList.add('l');
charsList.add('o');
This will yield hello
(I am using org.apache.commons.lang.ArrayUtils helper class):
final Character[] charactersArray =
charsList.toArray(new Character[charsList.size()]);
final char[] charsArray = ArrayUtils.toPrimitive(charactersArray);
System.out.println(String.valueOf(charsArray));
You can do it using toString() and RegExp without any loops and streams:
List<Character> list = Arrays.asList('a', 'b', 'c');
String s = list.toString().replaceAll("[,\\s\\[\\]]", "");