OK, so I have an ArrayList that I need to return as a String. Right now I am using this approach:
List customers = new ArrayList<>();
L
Anyone still stuck on this, try using a for-each loop.
ArrayList<String> list = new ArrayList<>(); // default size of 10
/*add elements to
the ArrayList*/
for(String element: list)
System.out.println(element);
You can override the toString() method and represent the output in whatever format you
Can directly convert list/set to string and perform action on it
customers.toString().replace("[", "").replace("]", "")
A possible solutions is:
String account = Arrays.toString(accounts.toArray());
return account.substring(1,account.length()-1);
Or do you override the toString
method to return the string as per you wanted.
You can try this.
String listAsStr = myList.toString(); // get list as string
listAsStr = listAsStr.substring(1,listAsStr.length()-1); // removing first and last bracket
This will return the string without first and last brackets.
If you want your output to look like: item1, item2, item3
Arrays.toString(customers.toArray()).replace('[', ' ').replace(']', ' ').trim()
If you want your output to look like: item1 item2 item3
Arrays.toString(customers.toArray()).replace('[', ' ').replace(']', ' ').replace(',', ' ').trim()